一、新建枚举
public enum CRUD
{
Create,
Retrieve,
Update,
Delete
}
二、新建特性类
public sealed class ChineseAttribute : Attribute
{
public string Chinese { get; set; }
public ChineseAttribute(string _chinese = "未汉化")
{
Chinese = _chinese;
}
}
三、利用反射获取特性
这里我们写一个枚举类的扩展方法
public static string GetChinese(this Enum value)
{
Type objType = value.GetType();
Type attrType = typeof(ChineseAttribute);
FieldInfo field = objType.GetField(value.ToString());
//利用反射找是否有【Chinese】特性
if (field.IsDefined(attrType))
{
var chinese = field.GetCustomAttribute<ChineseAttribute>();
return chinese.Chinese;
}
//没有定义Chinese特性,直接返回具体指
return value.ToString();
}
四、给枚举类添加特性
public enum CRUD
{
[Chinese("创建")]
Create,
[Chinese("读取")]
Retrieve,
[Chinese]
Update,
Delete
}
五、测试
static void Main(string[] args)
{
List<MyEnum.CRUD> values = new List<MyEnum.CRUD>
{
MyEnum.CRUD.Create,
MyEnum.CRUD.Delete,
MyEnum.CRUD.Retrieve,
MyEnum.CRUD.Update
};
foreach (var item in values)
{
Console.WriteLine(item.GetChinese());
}
Console.Read();
}
效果如下