标签:调用 ati inter 方法 ica standard voc div RoCE
参考资料:http://www.cnblogs.com/zuowj/p/7501896.html
1、通过NuGet下载Castle.Core
2、创建代理类并继承StandardInterceptor
参考代码如下
using Castle.DynamicProxy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class TestInterceptor : StandardInterceptor { /// <summary> /// 创建代理类 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T CreateProxy<T>() where T : class { ProxyGenerator generator = new ProxyGenerator(); var testa = generator.CreateClassProxy<T>(new TestInterceptor()); return testa; } /// <summary> /// 执行前 /// </summary> /// <param name="invocation"></param> protected override void PreProceed(IInvocation invocation) { Console.WriteLine(invocation.Method.Name + "执行前,入参:" + string.Join(",", invocation.Arguments)); } /// <summary> /// 执行中 /// </summary> /// <param name="invocation"></param> protected override void PerformProceed(IInvocation invocation) { Console.WriteLine(invocation.Method.Name + "执行中"); try { base.PerformProceed(invocation); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } /// <summary> /// 执行后 /// </summary> /// <param name="invocation"></param> protected override void PostProceed(IInvocation invocation) { Console.WriteLine(invocation.Method.Name + "执行后,返回值:" + invocation.ReturnValue); } } }
3、创建测试类
public class TestB { public virtual string GetResult() { string str = DateTime.Now + "TestB-GetResult"; Console.WriteLine(str); return str; } public virtual string GetResult2() { string str = DateTime.Now + "TestB-GetResult2"; Console.WriteLine(str); return str; } }
4、使用AOP方式调用方法
TestInterceptor.CreateProxy<TestB>().GetResult();
重点:virtual
Castle只会对virtual标记的虚方法进行代理
标签:调用 ati inter 方法 ica standard voc div RoCE
原文地址:https://www.cnblogs.com/jianghaidong/p/9964781.html