加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:12:46 所属栏目:百科 来源:网络整理
导读:我需要在我的项目中从任何枚举创建一个SelectList. 我有下面的代码,我从特定的枚举创建一个选择列表,但我想为任何枚举创建一个扩展方法.此示例检索每个Enum值上的DescriptionAttribute的值 var list = new SelectList( Enum.GetValues(typeof(eChargeType))
我需要在我的项目中从任何枚举创建一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读