2011-02-16 157 views
2

enum帮手泛型类在那里我有方法EnumDescription() 要调用它,我必须去这样EnumHelper<Enumtype>.EnumDescription(value) 我想要实现enum扩展,它基于我的枚举的辅助方法方法EnumDescription(this Enum value)EnumHelper<T>.EnumDescription(value)帮助枚举扩展方法

有一件事我被困住了。这里是我的代码:

public static string EnumDescription(this Enum value) 
{ 
    Type type = value.GetType(); 

    return EnumHelper<type>.EnumDescription(value); //Error here 
} 

我得到一个错误The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?)

,请问有什么可以做,使工作?

+0

你想给Enum一个很好的描述? – PostMan 2011-02-16 00:26:05

回答

3

我能想到的两个选项(可能还有更多)。

第一个选项:使通用扩展方法。 C#不允许enum作为通用约束,这意味着您需要运行时检查以确保该类型实际上是enum

public static string EnumDescription<T>(this T value) 
    where T : struct, IComparable, IConvertible, IFormattable 
{ 
    if (!typeof(T).IsEnum) 
     throw new InvalidOperationException("Type argument T must be an enum."); 

    return EnumHelper<T>.EnumDescription(value); 
} 

第二个选项:使用反射。这将会很慢(呃),尽管你可以从MethodInfo创建一个代理并将其缓存以便在Dictionary<Type, Delegate>或类似的地方重新使用。这种方式只会在第一次遇到特定类型时产生反射成本。

public static string EnumDescription(this Enum value) 
{ 
    Type t = value.GetType(); 
    Type g = typeof(EnumHelper<>).MakeGenericType(t); 
    MethodInfo mi = g.GetMethod("EnumDescription"); 
    return (string)mi.Invoke(null, new object[] { value }); 
} 
+0

你认为哪个选项更好? – Jop 2011-02-16 01:08:15

1

泛型是在编译时完成的。

您可以将您的方法更改为通用方法where T : struct或使用反射调用内部方法。