Jim*_*mbo 6 c# asp.net-mvc extension-methods enums selectlist
我需要建立一个SelectList从任何Enum在我的项目.
我有下面的代码,我从特定的枚举创建一个选择列表,但我想为任何枚举创建一个扩展方法.此示例检索DescriptionAttribute每个Enum值的值
var list = new SelectList(
Enum.GetValues(typeof(eChargeType))
.Cast<eChargeType>()
.Select(n => new
{
id = (int)n,
label = n.ToString()
}), "id", "label", charge.type_id);
Run Code Online (Sandbox Code Playgroud)
public static void ToSelectList(this Enum e)
{
// code here
}
Run Code Online (Sandbox Code Playgroud)
我认为你正在努力的是检索描述.我相信一旦你有那些你可以定义你的最终方法,给出你的确切结果.
首先,如果您定义了一个扩展方法,它将使用枚举的值,而不是枚举类型本身.我认为,为了便于使用,您希望在类型上调用方法(如静态方法).不幸的是,你不能定义那些.
你能做的是以下几点.首先定义一个方法来检索枚举值的描述,如果它有一个:
public static string GetDescription(this Enum value) {
string description = value.ToString();
FieldInfo fieldInfo = value.GetType().GetField(description);
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) {
description = attributes[0].Description;
}
return description;
}
Run Code Online (Sandbox Code Playgroud)
接下来,定义一个获取枚举的所有值的方法,并使用前面的方法查找我们想要显示的值,并返回该列表.可以推断出泛型参数.
public static List<KeyValuePair<TEnum, string>> ToEnumDescriptionsList<TEnum>(this TEnum value) {
return Enum
.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Select(x => new KeyValuePair<TEnum, string>(x, ((Enum)((object)x)).GetDescription()))
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
最后,为了便于使用,一种无需直接调用它的方法.但是泛型参数不是可选的.
public static List<KeyValuePair<TEnum, string>> ToEnumDescriptionsList<TEnum>() {
return ToEnumDescriptionsList<TEnum>(default(TEnum));
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以像这样使用它:
enum TestEnum {
[Description("My first value")]
Value1,
Value2,
[Description("Last one")]
Value99
}
var items = default(TestEnum).ToEnumDescriptionsList();
// or: TestEnum.Value1.ToEnumDescriptionsList();
// Alternative: EnumExtensions.ToEnumDescriptionsList<TestEnum>()
foreach (var item in items) {
Console.WriteLine("{0} - {1}", item.Key, item.Value);
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
哪个输出:
Value1 - My first value
Value2 - Value2
Value99 - Last one
Run Code Online (Sandbox Code Playgroud)