.net - 有关 Enum 扩展方法的帮助

标签 .net c#-4.0

我有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/

相关文章:

c# - 用另一个用户替换当前运行 EXE 的 Windows 用户

c# - 获得 Trace.indent 和 trace.unindent 等价物的 log4net 模式是什么

c# - RadioButton ContentStringFormat 不起作用

c# - 如何使用 StreamWriter 写入文件?

c# - 如何在暂停/持久化后正确加载工作流?

visual-studio-2010 - 频繁的VS 2010速度非常慢,并且在特定的解决方案/文件上崩溃?

c# - C# 控制台应用程序中的居中文本仅适用于某些输入

.net - 数据集中的可空 Int 列

c# - 长文本和 TextTrimming 时的 TextBlock 问题

c# - 基于key的KeyValueComparer