基础枚举
public enum Anima{
//默认值dog =0, 依次往下排,可自定义fox = 1, fish =2,tiger=3
dog,
fox,
fish,
tiger
}
高级用法,反射元数据
加了Description,就可以通过反射访问这些数据
public enum Anima{
//默认值dog =0, 依次往下排,可自定义fox = 1, fish =2,tiger=3
[Description("狗狗")]
[DataTest("汪汪")]
dog,
[Description("狐狸")]
[DataTest("吱吱")]
fox,
[Description("鱼")]
[DataTest("吐泡泡")]
fish,
[Description("老虎")]
[DataTest("嗷呜")]
tiger
}
//要多添加一个特性,可以加一个继承自Attribute的类
public class DataTest : Attribute
{
public string Data{get;set;}
public DataTest(){
Data = data;
}
public DataTest(){}
}
访问方法:
static class EnumExtensions{
public static string GetDescription(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
public static string GetData(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DataTest));
return customAttribute == null ? val.ToString() : ((DataTest)customAttribute).Data;
}
}
标签:Description,val,C#,fish,枚举,customAttribute,DataTest,public From: https://www.cnblogs.com/KevinSteven/p/17727932.html