【发布时间】: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<object, string > func),它对字典的每个值执行一些操作?
更新: 对应的结果是
var a = EnumToDictionary<Types>(FormatName);
//a[0] == "mytype1"
//a[1] == "mytype2"
//a[2] == "mytype3"
【问题讨论】:
-
你能把这段代码格式化一下吗?
-
你也可以问这个问题吗?到目前为止,您的整个帖子只是一个声明。有什么问题?
-
并请提供一些示例输入数据和相应的结果
-
你不想要一个 Func
而不是 Func