玩转.NET的Annotation(标记)技术

.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.");

}

屏幕的输出结果为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值