枚举到字典并格式化每个名称

时间:2011-04-12 08:46:00

标签: c# .net lambda delegates

我需要将枚举转换为字典,然后将格式转换为字典的每个名称(值)。

public static Dictionary<int, string> EnumToDictionary<TK>(Func<TK, string > func)
      {
        if (typeof(TK).BaseType != typeof(Enum))
              throw new InvalidCastException();


           return Enum.GetValues(
                typeof(TK))
                .Cast<Int32>()
                .ToDictionary(
                        currentItem => currentItem => Enum.GetName(typeof(TK), currentItem))
                 /*. func for each name */;
           }



      public enum Types {

            type1 = 0,
            type2 = 1,
            type3 = 2
         }


       public string FormatName(Types t) {
             switch (t) {
                         case Types.type1:
                                return "mytype1";

                         case Types.type2:
                              return "mytype2";

                         case Types.type3:
                              return "mytype3";

                           default:
                                return string.Empty;
                 }
           }

之后我需要做这样的事情:

var resultedAndFormatedDictionary = 
EnumToDictionary<Types>(/*delegate FormatName() for each element of dictionary() */);

如何定义和实现委托(Func<object, string > func),它为字典的每个值执行一些操作?

更新: 对应的结果是

var a = EnumToDictionary<Types>(FormatName);

   //a[0] == "mytype1"
   //a[1] == "mytype2"
   //a[2] == "mytype3"

1 个答案:

答案 0 :(得分:1)

从你的问题中猜想你想要实现从enum创建一个字典,其中enum值为int是键,而某些格式化的名称是值,对吗?

那么,首先你传入的函数应该以{{1​​}}作为参数,不是吗? 其次,抛出TK似乎有点奇怪。 InvalidCastException可能更合适(另请参阅this question
第三InvalidOperationException已经非常接近了:

ToDictionary

现在你可以这样称呼它:

public static Dictionary<int, string> EnumToDictionary<TK>(Func<TK, string> func)
{
     if (typeof(TK).BaseType != typeof(Enum))
        throw new InvalidOperationException("Type must be enum");

     return Enum.GetValues(typeof(TK)).Cast<TK>().ToDictionary(x => Convert.ToInt32(x), x => func(x));
}