特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性的定义与使用
1.创建一个自定义特性类
/// <summary>
/// 此处有特性可放置的使用限制,此刻只列举属性和Filed
/// 类名后缀必须以Attribute结尾
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class UpAttribute : Attribute
{
public bool Need { get; set; }
}
2.定义一个需要使用特性的类
public class Info
{
// 列举的是属性,若使用Filed,移除{get;set;}
public string msg1 { get; set; }
[Up(Need = false)]
public string msg2 { get; set; }
[Up(Need = true)]
public string msg3 { get; set; }
public Info(string a, string b, string c)
{
msg1 = a;
msg2 = b;
msg3 = c;
}
}
3.具体调用
static void Main(string[] args)
{
var info = new Info("aaaa", "bbbbb", "ccccc");
//特性通常配合反射使用,因为特性类型只有在对应的Type中的自定义属性中才能获取
foreach (var item in typeof(Info).GetProperties())
{
//此处使用Get方法获取比使用属性的优点在于可以直接将其实例化为对应特定类,方便获取其内部属性
if (item.GetCustomAttributes(true).Any(it => it is UpAttribute && (it as UpAttribute).Need))
{
Console.WriteLine(item.GetValue(info).ToString().ToUpper());
}
else
{
Console.WriteLine(item.GetValue(info).ToString());
}
}
Console.ReadKey();
}