小编Geo*_*ild的帖子

Castle Dynamic Proxy在从类中调用时不拦截方法调用

使用Castle的动态代理时,我遇到了一些(我认为)奇怪的行为.

使用以下代码:

class Program
{
    static void Main(string[] args)
    {
        var c = new InterceptedClass();
        var i = new Interceptor();

        var cp = new ProxyGenerator().CreateClassProxyWithTarget(c, i);

        cp.Method1();
        cp.Method2();

        Console.ReadLine();
    }
}

public class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine(string.Format("Intercepted call to: " + invocation.Method.Name));

        invocation.Proceed();
    }
}

public class InterceptedClass
{
    public virtual void Method1()
    {
        Console.WriteLine("Called Method 1");
        Method2();
    }

    public virtual void Method2()
    {
        Console.WriteLine("Called Method 2");
    }
}
Run Code Online (Sandbox Code Playgroud)

我期待获得输出:

  • 截获的电话:Method1
  • 称为方法1
  • 截获的电话:方法2
  • 称为方法2 …

c# castle-dynamicproxy dynamic-proxy

14
推荐指数
1
解决办法
6627
查看次数

标签 统计

c# ×1

castle-dynamicproxy ×1

dynamic-proxy ×1