【问题标题】:Proxy to interface + abstract class that intercepts only interface calls接口代理+只拦截接口调用的抽象类
【发布时间】:2017-03-01 18:24:38
【问题描述】:

我有以下结构:

abstract class AbstractClass{...}
interface Interface {...}
class MyClass : AbstractClass, Interface{...}

我想创建一个代理,它将 MyClass 作为目标,可以同时转换为 - AbstractClass 和 Interface,但是,它应该只拦截接口调用。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • AbstractClass 和 Interface 有重叠的方法吗?
  • 不,他们不知道,但接口方法事先不知道。

标签: castle-dynamicproxy


【解决方案1】:

花了一些时间,但感谢this SO question,我只能拦截接口方法。

给定:

public abstract class AbstractClass ...
public interface IBar ...
public class MyClass : AbstractClass, IBar ...

这个拦截器应该做你想做的事:

public class BarInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        var map = invocation.TargetType.GetInterfaceMap(typeof(IBar));
        var index = Array.IndexOf(map.TargetMethods, invocation.Method);

        if (index == -1)
        {
            // not an interface method
            invocation.Proceed();
            return;
        }

        Console.WriteLine("Intercepting {0}", invocation.Method.Name);
        invocation.Proceed();
    }
}

我的测试代码是:

var mc = new MyClass();
var gen = new ProxyGenerator();
var proxy = gen.CreateClassProxyWithTarget(typeof(MyClass), mc, new BarInterceptor());

((AbstractClass) proxy).GetString();
((AbstractClass) proxy).GetInt();
((IBar) proxy).GetItem();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 2010-12-01
  • 1970-01-01
相关资源
最近更新 更多