c#为枚举添加描述

在做UI时,下拉框往往会和某一枚举类型对应,如果我们想在代码中对下拉框的选项进行添加,并且不想每次修改枚举时都要修改下拉框的对应代码。就可以使用下面的特性来解决。

Description特性

namespace XFramework
{
    /// <summary>
    /// 为枚举提供自定义字符串
    /// </summary>
    [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
    public class DescriptionAttribute : Attribute
    {
        public string str;
        public DescriptionAttribute(string str)
        {
            this.str = str;
        }
    }
}

获取描述的静态方法

using System;
using System.Collections.Generic;

namespace XFramework
{
    public static partial class Utility
    {
        public static class Enum
        {
            /// <summary>
            /// 获取枚举的自定义字符串,需要结合DescriptionAttribute特性使用
            /// </summary>
            /// <typeparam name="T">枚举类型</typeparam>
            /// <returns>字符串集合</returns>
            public static List<string> GetDescription<T>() where T : System.Enum
            {
                Type attrType = typeof(DescriptionAttribute);
                Type type = typeof(T);
                var fields = type.GetFields();
                List<string> strArray = new List<string>();
                foreach (var item in fields) 
                {
                    if (item.FieldType != type)
                    {
                        continue;
                    }

                    Attribute attribute = Attribute.GetCustomAttribute(item, attrType);
                    if (attribute != null)
                    {
                        strArray.Add((attribute as DescriptionAttribute).str);
                    }
                    else
                    {
                        throw new Exception($"{type.Name} 的 {item.Name} 没有设置EnumStrAttribute特性");
                    }
                }
                return strArray;
            }
        }
    }
}

使用示例

public enum TestEnum
{
    [Description("葫芦小金刚")]TypeA,        
    [Description("金刚葫芦娃")]TypeB,         
    [Description("俄罗斯套娃")]TypeC,
}

public void Test()
{
	List<string> strList = Utility.Enum.GetDescription<TestEnum>()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值