如何为Enum类型参数创建扩展方法?

MD'*_*D's 5 c# extension-methods enums

以下是我将枚举值转换为Dictionary的代码.

public static Dictionary<string, string> EnumToDictionary<T>() where T : struct, IConvertible
    {
        var oResult = new Dictionary<string, string>();
        if (typeof(T).IsEnum)
            foreach (T oItem in Enum.GetValues(typeof(T)))
                oResult.Add(oItem.ToString(), oItem.ToString());
        return oResult;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的枚举

public enum MyEnum
{
    Value1,
    Value2,
    value3
}
Run Code Online (Sandbox Code Playgroud)

目前我正在调用这种方法

var result=EnumToDictionary<MyEnum>();
Run Code Online (Sandbox Code Playgroud)

但我需要使用那种方法

var result=MyEnum.EnumToDictionary();
Run Code Online (Sandbox Code Playgroud)

或任何其他方式,如字符串扩展方法.

Paw*_*ger 6

一般来说,您的问题与您想要创建通用扩展方法(这是可能的)但在调用此类方法时没有任何对象引用作为“this”参数发送的事实有关(这是不可能的)。因此,使用扩展方法不是实现您想要的目标的选项。

你可以这样做:

public static Dictionary<string, string> EnumToDictionary(this Enum @enum)
{
    var type = @enum.GetType();
    return Enum.GetValues(type).Cast<string>().ToDictionary(e => e, e => Enum.GetName(type, e));
}
Run Code Online (Sandbox Code Playgroud)

但这意味着您需要对枚举类的某个实例进行操作才能调用这样的扩展方法。

或者你可以这样做:

    public static IDictionary<string, string> EnumToDictionary(this Type t)
    {
        if (t == null) throw new NullReferenceException();
        if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

        string[] names = Enum.GetNames(t);
        Array values = Enum.GetValues(t);

        return (from i in Enumerable.Range(0, names.Length)
                select new { Key = names[i], Value = (int)values.GetValue(i) })
                    .ToDictionary(k => k.Key, k => k.Value.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

然后像这样调用它:

var result = typeof(MyEnum).EnumToDictionary();
Run Code Online (Sandbox Code Playgroud)