【发布时间】:2013-07-17 10:58:35
【问题描述】:
我正在寻找一种通过提供显示名称来查找枚举字段的方法。为了查找显示名称,我编写了这个片段,它将适当的字段(如果可用)作为任意类型返回给我。
if (!type.IsEnum) throw new ArgumentException("type");
return (from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
where field.IsDefined(typeof(DisplayNameAttribute))
let attribute = field.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute
where attribute != null && attribute.DisplayName.Equals(lookup, StringComparison.InvariantCultureIgnoreCase)
select (T)field.GetValue(null)).FirstOrDefault();
现在,我想这样称呼它:
MyEnum instance = MyEnum.GetFieldByDisplayName("my friendly name");
我尝试创建一个将“this Type”和“this Enum”作为参数的扩展方法,但它从未出现在 MyEnum 上。我做错了什么?
【问题讨论】:
-
你的意思是
typeof(MyEnum)? -
为了确定,你的扩展方法是
public static,第一个参数的类型是this MyEnum(或this Enum)并且在一个静态类中,在你的类中被引用想要使用该扩展方法并且您是在 Enum 的实例上使用它而不是 Enum 本身? -
....等等,Enum 的字段到底是什么?
-
我觉得你工作太努力了。你考虑过Enum.Parse吗?
-
@sq33G 枚举字段是具有值的条目,由编译器给定或自动生成。而 Enum.Parse 在我的情况下是无用的,因为我想通过它的描述而不是它的名称来检索枚举实例。
标签: c# .net enums extension-methods custom-attributes