获取没有target创建的接口代理的接口类型

问题描述 投票:0回答:1

考虑以下模型:

public interface IFooBase
{
    void DoSomething();
}

public interface IFoo : IFooBase
{
}

Castle.DynamicProxy 拦截器:

public class Proxy : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        // Here need to know from which interface the proxy 
        // is generate (IFooBase or IFoo).
    }
}

以及program.cs中使用CreateInterfaceProxyWithoutTarget生成的IFooBase和IFoo的代理:

var generator = new ProxyGenerator();
var proxy = new Proxy();
var fooBase = generator.CreateInterfaceProxyWithoutTarget<IFooBase>(proxy);
var foo = generator.CreateInterfaceProxyWithoutTarget<IFoo>(proxy);
fooBase.DoSomething();
foo.DoSomething();

Intercept 方法中,我需要知道代理是从哪个接口类型(IFooBase 或 IFoo)生成的。我知道的唯一选项是 inspiration.Method.DeclaringType 当然它总是返回 FooBase 类型。

c# castle-dynamicproxy
1个回答
0
投票

您可以使用此代码,我使用接口名称,您可以比较它们的类型

public void Intercept(IInvocation invocation)
{

    var types = invocation.GetType().GetInterfaces();
    bool hasIFoo = false;
    bool hasIFooBase = false;
    foreach (var type in types)
    {
        if (type.Name == "IFoo")
        {
            hasIFoo = true;
        }
        if (type.Name == "IFooBase")
        {
            hasIFooBase = true;
        }
    }
    if (hasIFoo && hasIFooBase)
        Console.WriteLine("Implement IFooBase");
    else if (hasIFoo)
        Console.WriteLine("Implement IFoo");
    else
        Console.WriteLine("Implement Nothing");

}
© www.soinside.com 2019 - 2024. All rights reserved.