首先定义一个自定义的属性类MyAttribute,该类需要继承Attribute
public class MyAttribute : Attribute
{
/// <summary>
/// 代码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Msg { get; set; }
public MyAttribute() { }
public MyAttribute(string code,string msg)
{
this.Code = code;
this.Msg = msg;
}
}
接下来定义一个使用MyAttribute的类AttributeTest
[MyAttribute("C01","类属性描述")]
public class AttributeTest
{
[My("C02","属性描述")] // 等价于 [MyAttribute("C02","属性描述")]
public string Field { get; set; }
[My("C03", "方法描述")]
public void Method()
{
}
}
测试读取AttributeTest的MyAttribute特性信息,代码如下:
static void Main(string[] args)
{
// 获取类的属性描述
var classIfno = typeof(AttributeTest).GetCustomAttribute<MyAttribute>();
// 获取指定属性的属性描述
var fieldIfno = typeof(AttributeTest).GetProperty("Field").GetCustomAttribute<MyAttribute>();
// 获取指定方法的属性描述
var methodIfno = typeof(AttributeTest).GetMethod("Method").GetCustomAttribute<MyAttribute>();
Console.WriteLine(classIfno.Msg + " " + fieldIfno.Msg + " " + methodIfno.Msg);
Console.ReadLine();
}
运行结果

转载自:https://www.cnblogs.com/Insist-Y/p/15319212.html。仅作为笔记使用