c# - 没有目标的 CaSTLe 接口(interface)代理

标签 c# castle-dynamicproxy

我正在尝试为一个没有目标的接口(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/

相关文章:

c# - 转发泛型类型定义

c# - C# 和 PHP 上的 Blowfish 加密产生不同的结果

c# - 不继承属性的接口(interface)代理

c# - 创建同时实现多个接口(interface)的动态代理

structuremap - 用结构图做拦截

c# - 使用 WebClient/HttpWebRequest 从 https 检索 XML - WP7

c# - 限制 TFS WorkItemStore.Query 的结果

c# - 使对象在代码中动态实现接口(interface)

c# - 如何加载引用 Win32 DLL 的程序集?

c# - 在 NHibernate 对象上使用动态代理