【问题标题】:Enum value not being recognised correctly枚举值未被正确识别
【发布时间】:2015-05-08 10:45:35
【问题描述】:

我有一些枚举,我设置如下:

public enum MyDefaultEnums
{
    [EnumMember(Value="My First Enum")]enum1,
    [EnumMember(Value="My Second Enum")]enum2,
}

然后我运行一个方法来检查给定的文本框 (tb) 以查看其中的文本。如果枚举列表中存在该值,则将其清除,如果不存在,则不理会它:

if (Enum.IsDefined(typeof(MyDefaultEnums), tb.Text) == true)
        {
            tb.Text = "";  
        }

但是,它不起作用。在运行时调试显示 MyDefaultEnums 将值作为 enum1 和 enum2 拾取,而不是我放入其中的字符串。谁能指出我哪里出错了? 谢谢

【问题讨论】:

  • 这个SO post 应该告诉你怎么做。
  • 嗯 - 该帖子暗示它正在为每个枚举属性单独分配一个 var (meminfo) (NameWithoutSpaces1) - 或者我错过了什么?随着我的枚举增长,这不是我想做的事情
  • 如果你必须这样做,那么通过 EnumMember(Value= ... 设置枚举值有什么意义?

标签: c# enums custom-attributes


【解决方案1】:

可以获取所有自定义属性值

var enumValues = typeof(MyDefaultEnums)
    .GetFields()
    .SelectMany(f => f.GetCustomAttributes(typeof(EnumMemberAttribute), false))
    .Cast<EnumMemberAttribute>()
    .Select(a => a.Value);

然后检查您的值是否在该数组中

if (enumValues.Contains(tb.Text))
    tb.Text = ""; 

你可以把这段代码放到帮助类中

public class Enum<TEnum>
{
    public static IEnumerable<string> GetMemberValues()
    {
        return typeof(TEnum).GetFields()
            .SelectMany(f => f.GetCustomAttributes(typeof(EnumMemberAttribute), false))
            .Cast<EnumMemberAttribute>()
            .Select(a => a.Value);
    }
}

现在检查很简单

if (Enum<MyDefaultEnums>.GetMemberValues().Contains(tb.Text))
    tb.Text = "";

您可以将它与任何标有EnumMember 属性的枚举一起使用

【讨论】:

  • IDE 无法识别 .GetFields()。 MSDN 暗示它在系统命名空间中,这显然是设置的,但它没有它
  • @Ricardinho 确保 GetFields 在您的框架中可用。是单声道吗?还要确保你没有错过typeof 部分
  • 我可以在 system.type 下的引用中看到它,我在项目中使用它,但它没有被识别。不知道你说的单声道是什么意思
  • 我看到的错误是“System.Type”不包含“GetFields”的定义,并且找不到接受“System.Type”类型的第一个参数的扩展方法“GetFields”(是您缺少 using 指令或程序集引用?)
  • 是的 - 我用过 typeof
猜你喜欢
  • 1970-01-01
  • 2013-09-19
  • 2017-08-30
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多