2014-01-23 124 views
5

以下是我的代码将枚举值转换为字典。如何为Enum类型参数创建扩展方法?

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; 
    } 

,这是我的枚举

public enum MyEnum 
{ 
    Value1, 
    Value2, 
    value3 
} 

目前我打电话像

var result=EnumToDictionary<MyEnum>(); 

这种方法,但我需要使用的方法类似

var result=MyEnum.EnumToDictionary(); 

或任何其他方式像字符串扩展方法DS。

+0

查看https://code.google.com/p/unconstrained-melody/ –

+1

@JonSkeet这不是他要问的。他希望有一种“扩展方法”适用于枚举类型,而不是枚举成员。这是不可能的,也没有真正需要这种语法。 –

+0

@EliArbel:哦,我明白了 - 就这个类型本身而言。对,不理我。 –

回答

3

一般来说你的问题与您要创建一个通用的扩展方法(这是可能的),但没有调用该方法时所发送的“这个”参数的任何对象引用的事实连接(这是不可能的)。 所以使用扩展方法不是实现你想要的选项。

你可以做某事像这样:

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)); 
} 

但是,这将意味着你需要在枚举类的一定实例操作来调用这样的扩展方法。

或者你可以这样做:

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()); 
    } 

然后调用它像这样:

var result = typeof(MyEnum).EnumToDictionary(); 
+0

谢谢。得到我想要的。 –

1

你可以写一个扩展方法,像:

public static IDictionary<string, string> ToDictionary(this Enum value) 
    { 
     var result = new Dictionary<string, string>(); 
      foreach (var item in Enum.GetValues(value.GetType())) 
       result.Add(Convert.ToInt64(item).ToString(), item.ToString()); 
     return result; 
    } 

但是要调用这样的扩展方法,您需要提供所需枚举的实例。例如。

 var dict = default(System.DayOfWeek).ToDictionary(); 
+0

我也尝试了很多方法来做到这一点。这也是其中之一,但我错过了'var dict = default(System.DayOfWeek).ToDictionary();'。 这对我来说是完美的。 谢谢。 –

相关问题