我有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
创建委托(delegate),但这会很慢(呃)。并将其缓存在 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 });
}
关于.net - 有关 Enum 扩展方法的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010966/