在C#中,您可以使用AOP(面向切面编程)来实现方法调用的拦截。常用的AOP库有PostSharp和AspectInjector。以下是使用AspectInjector库来实现方法调用拦截的示例:
dotnet add package AspectInjector
using AspectInjector.Broker;
[Injection(typeof(LoggingAspect))]
public class LoggingAspect : Attribute
{
[Advice(Kind.Around)]
public object HandleMethodCall(
[Argument(Source.Name)] string name,
[Argument(Source.Arguments)] object[] arguments,
[Argument(Source.Target)] Func<object[], object> method,
[Argument(Source.ReturnType)] Type retType)
{
Console.WriteLine($"Entering method {name}");
var result = method(arguments);
Console.WriteLine($"Leaving method {name}");
return result;
}
}
[LoggingAspect]
属性:using System;
public class MyClass
{
[LoggingAspect]
public void MyMethod(string arg1, int arg2)
{
Console.WriteLine($"Executing MyMethod with args {arg1} and {arg2}");
}
}
using System;
public class Program
{
public static void Main(string[] args)
{
var myClass = new MyClass();
myClass.MyMethod("Hello", 42);
}
}
运行程序,将会输出:
Entering method MyMethod
Executing MyMethod with args Hello and 42
Leaving method MyMethod
这样,您就可以在C#中拦截方法调用了。
领取专属 10元无门槛券
手把手带您无忧上云