帮助枚举扩展方法
我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?)
,请问有什么可以做,使工作?
我能想到的两个选项(可能还有更多)。
第一个选项:使通用扩展方法。 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 });
}
你认为哪个选项更好? – Jop 2011-02-16 01:08:15
泛型是在编译时完成的。
您可以将您的方法更改为通用方法where T : struct
或使用反射调用内部方法。
你想给Enum一个很好的描述? – PostMan 2011-02-16 00:26:05