在C#中,在运行时将多个接口组合为一个

本文关键字:一个 组合 接口 运行时 | 更新日期: 2023-09-27 18:29:42

我需要在一个运行时组合多个接口来创建一个新类型。例如,我可能有以下接口:

public interface IA{ 
}
public interface IB{ 
}

在运行时,我希望能够生成另一个接口,以便在以下sudo代码中工作:

Type newInterface = generator.Combine(typeof(IA), typeof(IB));
var instance = generator.CreateInstance(newInterface);
Assert.IsTrue(instance is IA);
Assert.IsTrue(instance is IB); 

有没有一种方法可以在.Net C#中做到这一点?

在C#中,在运行时将多个接口组合为一个

由于Castle Dynamic Proxy 的强大功能,这是可能的

public interface A
{
    void DoA();
}
public interface B
{
    void DoB();
}
public class IInterceptorX : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine(invocation.Method.Name + " is beign invoked");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var generator = new ProxyGenerator();
        dynamic newObject = generator.CreateInterfaceProxyWithoutTarget(typeof(A), new Type[] { typeof(B) }, new IInterceptorX());
        Console.WriteLine(newObject is A); // True
        Console.WriteLine(newObject is B); // True
        newObject.DoA(); // DoA is being invoked
    }
}