在做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>()
}