获取特性
注意:需 .NET Framaework 4.5 才能使用 GetCustomAttribute 方法
public class MyAttribute : System.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("类注释","类消息")]
class AttributeTest
{
[MyAttribute("属性注释", "属性消息")]
string Field{ set; get; }
[MyAttribute("方法注释", "方法消息")]
void Method()
{
return;
}
}
class program
{
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();
}
}