问题描述
public static Dictionary<int,string> GetEnumLocalizations<T>()
where T : struct
{
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(enumValue => (int)enumValue,enumObject => ((Enum)enumObject).ToLocalizedValue());
}
public static Dictionary<int,string> GetEnumDescriptions<T>()
where T : struct
{
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(enumValue => (int)enumValue,enumObject => ((Enum)enumObject).GetDescription());
}
public static string GetDescription(this Enum value)
{
return ...
}
public static string ToLocalizedValue(this Enum value)
{
return ...
}
如果我没记错的话,应该可以将 GetEnumLocalizations()
和 GetEnumDescriptions()
合并为一个函数,并使用委托参数来解析 ((Enum)enumObject).ToLocalizedValue())
和 ((Enum)enumObject).GetDescription())
部分。
这可能吗?我在尝试这样做时被卡住了。在伪代码中,我想的是这样的:
public static Dictionary<int,string> GetEnumValues<T>(delegate someFunction)
where T : struct
{
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(enumValue => (int)enumValue,someFunction);
}
解决方法
当然,就用这个:
public static Dictionary<int,string> GetEnumValues<T>(Func<Enum,string> someFunction)
where T : struct
{
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(enumValue => (int)enumValue,enumObject => someFunction((Enum)enumObject);
}
现在你应该可以这样称呼它了:
GetEnumValues<MyEnum>(x => x.ToLocalizedValue());