.NET Core类库System.Reflection.DispatchProxy实现简易Aop的方法

2019-05-25 08:37:56王旭

2|3使用方法

 class Program
 {
  static void Main(string[] args)
  {
   var poxy1 = (targetInterface)ProxyGenerator.Create(typeof(targetInterface), new SampleProxy("coreproxy1"));
   poxy1.Write("here was invoked"); //---> "here was invoked by coreproxy1"

   var poxy2 = (targetInterface)ProxyGenerator.Create(typeof(targetInterface), typeof(SampleProxy), "coreproxy2");
   poxy2.Write("here was invoked"); //---> "here was invoked by coreproxy2"

   var poxy3 = ProxyGenerator.Create<targetInterface, SampleProxy>("coreproxy3");
   poxy3.Write("here was invoked"); //---> "here was invoked by coreproxy3"
  }
 }


 public class SampleProxy : IInterceptor
 {
  private string proxyName { get; }

  public SampleProxy(string name)
  {
   this.proxyName = name;
  }

  public object Intercept(MethodInfo method, object[] parameters)
  {
   Console.WriteLine(parameters[0] + " by " + proxyName);
   return null;
  }
 }

 public interface targetInterface
 {
  void Write(string writesome);
 }

3|0总结

总结一下就是,微软爸爸给我们的这个轮子还是即轻便又很好用的。

本文的实例代码可以在我的github上找到:https://github.com/ElderJames/CoreProxy

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。