本文參考文章:https://www.cnblogs.com/lwhkdash/p/6728611.html
針對參考,寫了一個方便的框架供大家使用:
github地址:https://github.com/lishuangquan1987/Tony.Interceptor
使用方法:
使用
1.定義一個類實現IInterceptor
:
這樣你就能處理方法調用前 BeforeInvoke
和方法調用後AfterInvoke
class LogInterceptor : IInterceptor
{
public void AfterInvoke(object result, MethodBase method)
{
Console.WriteLine($"執行{method.Name}完畢,返回值:{result}");
}
public void BeforeInvoke(MethodBase method)
{
Console.WriteLine($"準備執行{method.Name}方法");
}
}
2.在你想攔截的方法或者方法所屬的類上面打標籤
首先,你想攔截的方法所屬的類必須繼承自 ContextBoundObject
然後你必須用 InterceptorAttribute
標籤去修飾 實例 方法或者類
假如你的標籤打在類上面,則默認攔截所有的公開實例方法
假如你不想攔截打了標籤的類中的某個方法,你可以在方法上加上這個標籤 InterceptorIgnoreAttribute
,這樣,它就不會被攔截
[Interceptor(typeof(LogInterceptor))]
public class Test:ContextBoundObject
{
public void TestMethod()
{
Console.WriteLine("執行TestMethod方法");
}
public int Add(int a, int b)
{
Console.WriteLine("執行Add方法");
return a + b;
}
[InterceptorIgnore]
public void MethodNotIntercept()
{
Console.WriteLine("MethodNotIntercept");
}
}
3.創建類的實例並調用方法
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.TestMethod();
test.Add(5,6);
test.MethodNotIntercept();
Console.Read();
}
}
本文所用的框架源碼下載:https://github.com/lishuangquan1987/Tony.Interceptor