引言

  假如现在我们有这样在这个示例中我将使用尽可能简单的逻辑实现所有功能需求,这将更突出我们所要解决的核心问题。例子是一个简单计算器类:

public class Calculator
"Add(", x, y);
  int result = x + y;
  Console.WriteLine(" = ", result);
  return result;
 "Add(", x, y);
  DateTime TimeBegin = System.DateTime.Now;
  int result = x + y;
  TimeSpan TimeInter =System.DateTime.Now-TimeBegin;
  Console.Write(" [", TimeInter);
  Console.WriteLine(" = ", result);
  return result;
 "Add(", x, y);
  DateTime TimeBegin = System.DateTime.Now;
  int result = x + y;
  TimeSpan TimeInter =System.DateTime.Now-TimeBegin;
  Console.Write(" [", TimeInter);
  Console.WriteLine(" = ", result);
  return result;
 "Subtract(", x, y);
  DateTime TimeBegin = System.DateTime.Now;
  int result = x - y;
  TimeSpan TimeInter =System.DateTime.Now-TimeBegin;
  Console.Write(" [", TimeInter);
  Console.WriteLine(" = ", result);
  return result;
 "Number(", x, y);
 // " 运行时间[", TimeInter);
 // Console.WriteLine(" 运行结果= ", result);
 // "Number(", x, y);
  " 运行时间[", TimeInter);
   Console.WriteLine(" 运行结果= ", result);
  " 运行时间[", TimeInter);
   Console.WriteLine(" 运行结果= ", returnValue);
   base.PostProceed(invocation, ref returnValue, arguments);
  "Number(", args[0], args[1]);
   TimeBegin=System.DateTime.Now;
   base.PreProceed(invocation, args);
  }
  public override object Intercept(IInvocation invocation, params object[] args)
  {
   PreProceed(invocation, args);
   object retValue = invocation.Proceed( args );
   PostProceed(invocation, ref retValue, args);
   return retValue;
  }
 }
}
  4、使用Castle.DynamicProxy调用

ProxyGenerator generator = new ProxyGenerator();
object proxy = generator.CreateClassProxy(typeof(Calculator), new ProxyInterceptor());
ICalculator ICalCastle=proxy as ICalculator;
ICalCastle.Add(5,3);
ICalCastle.Subtract(7,2);


  实现过程:首先通过代码生成完成一个代理类,该代理类继承自要织入的类。然后在代理类中覆盖要拦截的方法,并在覆盖的方法中封装Invocation对象,并传给用户传入的Intercepter对象的Intercept方法。在Intercept方法依次调用Intercepter的PreProcess,通过Invocation传入的Delegate指向的回调函数,Intercepter的PostProcess方法,从而达到拦截的目的。

  意义

  在aop领域 可以将日志,事务,缓存等附加功能用此实现。

 

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com