c# – SelectList扩展方法的通用枚举

我需要在我的项目中从任何枚举创建一个SelectList.

我有下面的代码,我从特定的枚举创建一个选择列表,但我想为任何枚举创建一个扩展方法.此示例检索每个Enum值上的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
}

解决方法

我认为你正在努力的是检索描述.我相信一旦你有那些你可以定义你的最终方法,给出你的确切结果.

首先,如果您定义了一个扩展方法,它将使用枚举的值,而不是枚举类型本身.我认为,为了便于使用,您希望在类型上调用方法(如静态方法).不幸的是,你不能定义那些.

你能做的是以下几点.首先定义一个方法来检索枚举值的描述​​,如果它有一个

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

最后,一种无需直接调用它的方法.但是泛型参数不是可选的.

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

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么