作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我需要从项目中的任何 Enum
创建一个 SelectList
。
我在下面的代码中从特定枚举创建了一个选择列表,但我想为任何枚举创建一个扩展方法。此示例检索每个枚举值的 DescriptionAttribute
的值
var list = new SelectList(
Enum.GetValues(typeof(eChargeType))
.Cast<eChargeType>()
.Select(n => new
{
id = (int)n,
label = n.ToString()
}), "id", "label", charge.type_id);
引用 this post ,我该如何进行?
public static void ToSelectList(this Enum e)
{
// code here
}
最佳答案
我认为您正在努力解决的是描述的检索。我敢肯定,一旦您有了这些,您就可以定义 final方法来给出您的确切结果。
首先,如果您定义了一个扩展方法,它会作用于枚举的值,而不是枚举类型本身。而且我认为,为了便于使用,您想调用类型上的方法(如静态方法)。不幸的是,您无法定义它们。
您可以执行以下操作。首先定义一个方法来检索枚举值的描述,如果它有一个:
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;
}
接下来,定义一个获取枚举所有值的方法,并使用前面的方法查找我们想要显示的值,并返回该列表。可以推断通用参数。
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();
}
最后,为了方便使用,一个直接调用它的方法没有值(value)。但是通用参数不是可选的。
public static List<KeyValuePair<TEnum, string>> ToEnumDescriptionsList<TEnum>() {
return ToEnumDescriptionsList<TEnum>(default(TEnum));
}
现在我们可以这样使用它了:
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();
哪些输出:
Value1 - My first value
Value2 - Value2
Value99 - Last one
关于c# - 通用枚举到 SelectList 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145161/
我是一名优秀的程序员,十分优秀!