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

C# 在C中运行时将多个接口合并为一个#,c#,types,interface,C#,Types,Interface,我需要在运行时组合多个接口来创建一个新类型。例如,我可能有以下接口: public interface IA{ } public interface IB{ } 在运行时,我希望能够生成另一个接口,以便在以下sudo代码中工作: Type newInterface = generator.Combine(typeof(IA), typeof(IB)); var instance = generator.CreateInstance(newInterface); Assert.IsTrue

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

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#中有没有办法做到这一点?

这是可能的,因为Castle动态代理的强大功能

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
    }
}

这是可能的,因为城堡动态代理的力量

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
    }
}

这没有什么意义,因为不能创建接口类型的对象。简单的方法是创建一个实现两个接口的类。@HansPassant如果使用动态对象框架,就可以创建动态对象。看看Castle Dynamic Proxiest这没有什么意义,您无法创建接口类型的对象。简单的方法是创建一个实现两个接口的类。@HansPassant如果使用动态对象框架,就可以创建动态对象。在问这个问题之前,我仔细查看了CreateInterfaceProxy WithoutTarget的重载,没有将类型数组视为第二个参数。啊!谢谢你的帮助。令人烦恼的是,在问这个问题之前,我查看了CreateInterfaceProxy WithoutTarget的重载,没有将类型数组视为第二个参数。啊!谢谢你的帮助。