【问题标题】:Extension method to lookup enumeration field by display name通过显示名称查找枚举字段的扩展方法
【发布时间】: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


【解决方案1】:

考虑您的首选用途

MyEnum instance = MyEnum.GetFieldByDisplayName("my friendly name");

您试图在枚举类型上定义静态方法,而不是扩展方法。扩展方法出现在一个类型的实例上,而不是出现在类型本身上。

如果你定义了一个扩展类型,你可以像这样使用它

MyEnum instance = MyEnum.SomeValue.GetFieldByDisplayName("my friendly name");

AFAIK 您无法定义允许您随意使用它的方法(或其他方法),因为您无法在枚举类型上定义静态方法。

【讨论】:

    【解决方案2】:

    看看这个 - Enumeration extension methods

    要显示扩展方法,重要的是如何编写方法的原型,而不是方法体。

    所以,你应该有这样的东西:

    public static void Something(this Enum e)
    {
        // code here
    }
    

    【讨论】:

    • 哦,你真正想要的是查看 Enum 类型的扩展,而不是“实例”
    • @Atrotygma 那么这看起来更像是一个类型的静态方法而不是一个类型的扩展方法。如果你想拥有一个扩展方法,那么你最终将拥有一个带有 (this Type) 的方法,然后像 typeof(Enum).MyMethod 一样调用它。
    • @dutzu 这不允许 OP 像 MyEnum.SomeExtensionMethod(...) 一样使用它。
    • 您应该创建一个具有所需方法的静态类,作为静态方法以及所需类型 Enum 的成员。以此为例:msdn.microsoft.com/en-us/library/bb383974.aspx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多