轻量级AOP框架-移植python的装饰器(Decorator)到C#(编码篇)
2010-01-08 00:00:00 来源:WEB开发网将这部分IL翻译一下,如果我们定义了一个方法public virtual string Test(string p),那么自动生成的方法大致会像下面一样。
01 public override string Test(string p) {
02 Type type = typeof(TestClass);
03 MethodInfo thisMethod = type.GetMethod("Test", new Type[] { typeof(string) });
04 MetaCacheItem metaCacheItem = MetaCache.Get(type);
05 MetaMethodInfo thisMetaMethod = metaCacheItem.Methods.FirstOrDefault(e => e.Method == thisMethod);
06 Func<object, object[], object> fun = TypeFactory.CreateGenericInvoker(thisMetaMethod.Method);
07 object[] parameters = new object[] { p };
08 foreach (var item in thisMetaMethod.Filters) {
09 DecoratorContext context = new DecoratorContext(fun, this, parameters);
10 fun = item.Execute(context);
11 }
12 return (string)fun(this, parameters);
13 }
五. 框架测试
首先测试功能,我们仍然以上篇中第一个Python代码为例,想办法达到一样的效果,准备的代码如下:
01 /// <summary>
02 /// 和@logger功能一致的LoggerAttribute实现
03 /// </summary>
04 public class LoggerAttribute : Attribute, IDecoratorFilter {
05 public string Name { get; private set; }
06
07 public LoggerAttribute(string name) {
08 Name = name;
09 }
10
11 #region IDecoratorFilter Members
12
13 public Func<object, object[], object> Execute(DecoratorContext context) {
14 return (instanse, parameters) => {
15 Console.WriteLine("User is {0}.", Name);
16 Console.WriteLine("Start Logging.");
17 var result = context.Invoker(instanse, parameters);
18 Console.WriteLine("End Logging.");
19 return result;
20 };
21 }
22
23 #endregion
24 }
25
26 /// <summary>
27 /// 和@debuger功能一致的DebuggerAttribute实现
28 /// </summary>
29 public class DebuggerAttribute : Attribute, IDecoratorFilter {
30 public string Name { get; private set; }
31
32 public DebuggerAttribute(string name) {
33 Name = name;
34 }
35
36 #region IDecoratorFilter Members
37
38 public Func<object, object[], object> Execute(DecoratorContext context) {
39 return (instanse, parameters) => {
40 Console.WriteLine("Debug {0}", Name);
41 Console.WriteLine("Start Debug.");
42 var result = context.Invoker(instanse, parameters);
43 Console.WriteLine("End Debug.");
44 return result;
45 };
46 }
47
48 #endregion
49 }
50
51 public class TestClass {
52 [Logger("Leven")]
53 [Debugger("test")]
54 public virtual string Test() {
55 Console.WriteLine("Method TestClass::Test() called.");
56 return "I am Result.";
57 }
58 }
- ››AOP的两个应用:实体集更新(DateEntityListUpdate...
- ››AOP的两个应用:实体集更新(DateEntityListUpdate...
- ››轻量级数据交换格式 JSON轻松入门
- ››轻量级系统 Lubuntu 10.04 发布
- ››AOP 的利器:ASM 3.0 介绍
- ››轻量级AOP框架-移植python的装饰器(Decorator)到C...
- ››轻量级AOP框架-移植python的装饰器(Decorator)到C...
- ››轻量级开发的成功秘诀,第 4 部分: 轻量级容器的比...
- ››轻量级开发的成功秘诀,第 5 部分: 在保守公司进行...
- ››轻量级开发的成功秘诀,第 6 部分: 持久性策略
- ››轻量级开发的成功秘诀,第 7 部分: Java 替代方案...
- ››轻量级开发的成功秘诀,第 8 部分: Seaside
更多精彩
赞助商链接