Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在使用代理时不调用我的拦截器?_C#_Proxy_Interceptor_Castle Dynamicproxy - Fatal编程技术网

C# 为什么在使用代理时不调用我的拦截器?

C# 为什么在使用代理时不调用我的拦截器?,c#,proxy,interceptor,castle-dynamicproxy,C#,Proxy,Interceptor,Castle Dynamicproxy,我试图使用Castle DynamicProxy,但从教程(如)中获得灵感的最基本的代码失败了 为了使事情更简单,我将所有代码放在一个文件中,因此它足够短,可以复制粘贴到这里: namespace UnitTests { using Castle.DynamicProxy; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; [TestClass] public class

我试图使用Castle DynamicProxy,但从教程(如)中获得灵感的最基本的代码失败了

为了使事情更简单,我将所有代码放在一个文件中,因此它足够短,可以复制粘贴到这里:

namespace UnitTests
{
    using Castle.DynamicProxy;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;

    [TestClass]
    public class DemoTests
    {
        [TestMethod]
        public void TestHelloMethodThroughProxy()
        {
            var proxy = new ProxyGenerator().CreateClassProxy<Demo>(new DemoInterceptor());
            var actual = proxy.SayHello();
            var expected = "Something other";

            Assert.AreEqual(expected, actual);
        }
    }

    [Serializable]
    public class DemoInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            invocation.ReturnValue = "Something other";
        }
    }

    public class Demo
    {
        public string SayHello()
        {
            return "Hello, World!";
        }
    }
}
命名空间单元测试
{
使用Castle.DynamicProxy;
使用Microsoft.VisualStudio.TestTools.UnitTesting;
使用制度;
[测试类]
公开课降级
{
[测试方法]
public void TestHelloMethodThroughProxy()
{
var proxy=new ProxyGenerator().CreateClassProxy(new DemoInterceptor());
var-actual=proxy.SayHello();
var expected=“其他东西”;
断言.AreEqual(预期、实际);
}
}
[可序列化]
公共类DemoInterceptor:IInterceptor
{
公共无效拦截(IInvocation调用)
{
invocation.ReturnValue=“其他”;
}
}
公开课演示
{
公共字符串SayHello()
{
返回“你好,世界!”;
}
}
}
代码由单个单元测试组成,该测试生成类的代理,然后通过代理调用该类的方法

代理旨在通过简单地分配结果值而不调用原始方法来绕过对原始方法的调用

如果我替换
invocation.ReturnValue=“Something other”通过
抛出新的NotImplementedException(),测试结果仍然完全相同,并且不会引发异常,这表明可能没有调用代码。在调试模式下,
Intercept
方法中的断点也不会到达


我需要做什么才能调用拦截器?

Castle Windsor只能拦截接口或虚拟成员。您的
Demo.SayHello
方法未标记为虚拟,因此不会被拦截

将方法标记为虚拟或使用接口

提及