我正在尝试为一个没有目标的接口(interface)创建一个代理,当我在生成的代理上调用一个方法时,我总是得到一个 System.NullReferenceException
,尽管 拦截器 总是被很好地调用。
这是接口(interface)和拦截器的定义:
internal class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine(invocation.Method.Name);
}
}
public interface IMyInterface
{
int Calc(int x, int y);
int Calc(int x, int y, int z);
}
这是主程序:
class Program
{
static void Main(string[] args)
{
ProxyGenerator generator = new ProxyGenerator();
IMyInterface proxy = (IMyInterface) generator.CreateInterfaceProxyWithoutTarget(
typeof(IMyInterface), new MyInterceptor());
proxy.Calc(5, 7);
}
}
拦截器被调用,但我从 DynamicProxyGenAssembly2 得到一个异常。为什么?
最佳答案
问题出在 Calc
方法的返回类型中,它是原始 Int32
。一旦您未在拦截器中指定返回值,它将返回 null
,因此,当代理尝试将该值转换为 Int32
时,它将抛出一个 空指针异常
。
要解决此问题,您应该在 intercept
方法中设置返回值,例如invocation.ReturnValue = 0;
关于c# - 没有目标的 CaSTLe 接口(interface)代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546815/