【问题标题】:Enum to dictionary and format each name枚举到字典并格式化每个名称
【发布时间】:2011-04-12 08:46:00
【问题描述】:

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

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&lt;object, string &gt; func),它对字典的每个值执行一些操作?

更新: 对应的结果是

var a = EnumToDictionary<Types>(FormatName);

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

【问题讨论】:

  • 你能把这段代码格式化一下吗?
  • 你也可以问这个问题吗?到目前为止,您的整个帖子只是一个声明。有什么问题?
  • 并请提供一些示例输入数据和相应的结果
  • 你不想要一个 Func 而不是 Func

标签: c# .net lambda delegates


【解决方案1】:

从你想要实现的问题中猜测,从枚举中创建一个字典,其中枚举值作为 int 是键,它的一些格式化名称是值,对吧?

嗯,首先你传入的函数应该将TK 作为参数,不是吗?
其次,抛出InvalidCastException 似乎有点奇怪。 InvalidOperationException 可能更合适(另请参阅this question
第三个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));
}

现在你可以这样称呼它:

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

【讨论】:

  • 无法编译 - 'System.Linq.ParallelEnumerable.Cast(System.Linq.ParallelQuery)' 是一个'方法',在给定的上下文中无效'跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 2011-07-31
  • 2014-11-27
  • 1970-01-01
相关资源
最近更新 更多