【问题标题】:Castle Interface Proxy without target没有目标的城堡接口代理
【发布时间】:2013-12-13 00:19:59
【问题描述】:

我正在尝试为没有目标的接口创建代理,当我在生成的代理上调用方法时,我总是得到 System.NullReferenceException,尽管 拦截器 总是被很好地调用。

这里是接口和拦截器的定义:

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 得到一个异常。为什么?

【问题讨论】:

    标签: c# castle-dynamicproxy


    【解决方案1】:

    问题在于Calc 方法的返回类型,它是一个原始Int32。一旦你没有在你的拦截器中指定返回值,那么它将返回null,因此,当代理尝试将该值转换为Int32时,它会抛出一个NullPointerException

    要解决问题,您应该在intercept方法中设置返回值,例如invocation.ReturnValue = 0;

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 2011-03-28
      • 1970-01-01
      • 2010-11-28
      • 2018-03-14
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多