1.去NuGet下載 Castle.Core.dll
2.建一個普通的類。注意:本類2個方法,測試是否走攔截器。這里只有標記Virtual才能實現方法攔截。代碼如下:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Castle { public class TestInterceptor { public virtual void MethodInterceptor() { Console.WriteLine("走過濾器"); } public void NoInterceptor() { Console.WriteLine("沒有走過濾器"); } } }
3.攔截器 重寫攔截器方法:
PreProcced,在進入攔截的方法之前調用。PerformProceed,在攔截的方法返回時調用。PostProcced,在攔截的方法運行完成后調用。 代碼如下:

using Castle.DynamicProxy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Castle { public class Interceptor: StandardInterceptor { /// <summary> /// 調用前的攔截器 /// </summary> /// <param name="invocation"></param> protected override void PreProceed(IInvocation invocation) { Console.WriteLine("調用前的攔截器,方法名是:{0}。", invocation.Method.Name);// 方法名 獲取當前成員的名稱。 } /// <summary> /// 攔截的方法返回時調用的攔截器 /// </summary> /// <param name="invocation"></param> protected override void PerformProceed(IInvocation invocation) { Console.WriteLine("攔截的方法返回時調用的攔截器,方法名是:{0}。", invocation.Method.Name); base.PerformProceed(invocation); } /// <summary> /// 調用后的攔截器 /// </summary> /// <param name="invocation"></param> protected override void PostProceed(IInvocation invocation) { Console.WriteLine("調用后的攔截器,方法名是:{0}。", invocation.Method.Name); } } }
4.調用

using Castle.DynamicProxy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Castle { class Program { static void Main(string[] args) { ProxyGenerator generator = new ProxyGenerator();//實例化【代理類生成器】 Interceptor interceptor = new Interceptor();//實例化【攔截器】 //使用【代理類生成器】創建Person對象,而不是使用new關鍵字來實例化 TestInterceptor test = generator.CreateClassProxy<TestInterceptor>(interceptor); Console.WriteLine("當前類型:{0},父類型:{1}", test.GetType(), test.GetType().BaseType); Console.WriteLine(); test.MethodInterceptor(); Console.WriteLine(); test.NoInterceptor(); Console.WriteLine(); Console.ReadLine(); } } }
5.輸出結果: