.NET的Annotation(标记)技术跟JAVA中的Annotation技术非常类似,在对于代码进行元信息标记的时候特别有效,配合类反射、动态调用等技术可以非常轻松地实现基于切面的编程(AOP)、依赖注入等高级主题,本文将简单地通过一个例子带大家体验一下.NET的Annotation(标记)技术。
首先定义属性标记的实现类 MethodInTransactionAttribute :
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class MethodInTransactionAttribute : Attribute
{
private string m_inTransaction = null;
public MethodInTransactionAttribute(string inTransaction)
{
this.InTransaction = inTransaction;
}
public string InTransaction
{
get
{
return (this.m_inTransaction);
}
set
{
this.m_inTransaction = value;
}
}
接下来实现一个测试方法的基类TestClass:
public sealed class TestClass
{
[MethodInTransaction("TRUE")]
public void Method1()
{
System.Console.WriteLine("Method1");
}
[MethodInTransaction("FALSE")]
public void Method2()
{
System.Console.WriteLine("Method1");
}
[MethodInTransaction("NOTKNOWN")]
public void Method3()
{
System.Console.WriteLine("Method3");
}
}
最后使用类反射技术进行方法标记检查:
static void Main(string[] args)
{
Type typeForTest = typeof(TestClass);
MethodInfo [] mis = typeForTest.GetMethods();
foreach (MethodInfo mi in mis)
{
string methodName = mi.Name;
System.Console.Write(methodName + ": ");
object [] customAttributes = mi.GetCustomAttributes(typeof(MethodInTransactionAttribute), false);
if (customAttributes.Length == 0)
{
System.Console.WriteLine("Not existed!!!");
}
else
{
foreach (MethodInTransactionAttribute attrib in customAttributes)
{
System.Console.WriteLine(attrib.InTransaction);
}
}
}
// console write line for ending
System.Console.WriteLine("End of program.");
}
屏幕的输出结果为: