反射(2)

反射例子——获取枚举的备注信息

static void Main(string[] args)
{
var str = ColorType.Blue.GetRemark();

Console.WriteLine(str);
Console.ReadLine();
}

public static string GetRemark(this Enum em)
{
Type type = em.GetType();
FieldInfo fieldInfo = type.GetField(em.ToString());
if (fieldInfo == null)
{
return string.Empty;
}
object[] attrs = fieldInfo.GetCustomAttributes(typeof(RemarkAttribute), false);
string name = string.Empty;
foreach (RemarkAttribute attr in attrs)
{
name = attr.Remark;
}
return name;
}

public class RemarkAttribute : Attribute
{
public RemarkAttribute(string remark)
{
this.Remark = remark;
}

public string Remark { get; set; }
}

public enum ColorType
{
[Remark("黑色")] Black = 1,

[Remark("蓝色")] Blue = 2,

[Remark("红色")] Red = 3
}

结果:蓝色

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

         

原文地址:https://www.cnblogs.com/xiao-wo-niu/p/11597441.html