特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、属性、字段、结构、枚举、组件等)的行为信息的声明性标签。
AttributeUsage:描述如何使用自定义的Attribute类,规定了可以应用到的程序中的元素类型。
Conditional:对方法或者属性增加一个条件标记,依赖于指定的预定义是否存在。
Obsolete:标注过时的元素,不应该被使用。
下面是具体的使用例子,通过定义一个新的Attribute类来说明分析。
#define TestAttribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
namespace StudyCSharpConsole
{
//AttributeUsage:用来限制和描述自定义Attribute类,规定了Attribute类适用的应用范围。
//下面指明:适用于类和方法,只允许指定一个Attribute实例,无法由派生类和重写成员继承。
//后两个是可选的,默认设定为false。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
class NewAttribute : Attribute
{
private string name = string.Empty;
private string version = string.Empty;
private int count = 0;
public string Name
{
get { return name; }
set { name = value; }
}
public string Version
{
get { return version; }
set { version = value; }
}
public int Count
{
get { return count; }
set { count = value; }
}
}
[New(Name = "TestClass", Version = "1.0.0", Count = 1)]
class TestClass
{
[Conditional("TestAttribute")]
public void TestMethod()
{
Console.WriteLine("TestMethod is run.");
}
[New(Name = "TestMethod2", Version = "1.0.1", Count = 2)]
public void TestMethod2()
{
Console.WriteLine("TestMethod2 is run.");
}
//标注该方法不推荐使用,在调用处编译器当做错误处理(false的时候当做警告)
[Obsolete("TestMethod3 is Obsolete.", true)]
public void TestMethod3()
{
Console.WriteLine("TestMethod3 is run.");
}
}
class Program
{
static void Main(string[] args)
{
TestClass testClass = new TestClass();
//此处会报类似于后面的编译错误(“TestMethod3()”已过时:“TestMethod3 is Obsolete.”)。
//testClass.TestMethod3();
//预定义了TestAttribute的场合,下面的方法会被调用,否则会忽略该方法的调用。
testClass.TestMethod();
//取得类的特性信息
NewAttribute attr = (NewAttribute)Attribute.GetCustomAttribute(typeof(TestClass), typeof(NewAttribute));
Console.WriteLine(attr.Name + "," + attr.Version + "," + attr.Count);
//先取得类的方法列表
MethodInfo[] methods = typeof(TestClass).GetMethods();
foreach (MethodInfo method in methods)
{
//取得每个方法的特性并显示。
NewAttribute methodAttr = (NewAttribute) Attribute.GetCustomAttribute(method, typeof(NewAttribute));
if (methodAttr == null)
{
continue;
}
Console.WriteLine(methodAttr.Name + "," + methodAttr.Version + "," + methodAttr.Count);
}
}
}
}