简体   繁体   English

实例化实现接口C#的通用类型

[英]Instantiate a generic type which implements an Interface C#

I have the following generic type: 我有以下通用类型:

public class CommandFlow<T> : IFlow where T: IFlow
{
    private T _flow;
    public CommandFlow(T flow)
    {
        _flow= flow;
    }    
}

where IFlow has some implementations: StaticFlow, DynamicFlow, CombinedFlow. IFlow具有一些实现:StaticFlow,DynamicFlow,CombinedFlow。 I want to instantiate the generic type with Active.CreateInstance, so I have the code: 我想用Active.CreateInstance实例化泛型类型,所以我有代码:

var flowType = typeof(CommandFlow<>).MakeGenericType(nominalFlowType);
//nominalFlowType is one of the types: StaticFlow, DynamicFlow, CombinedFlow

Then I try to instantiate the generic type: 然后,我尝试实例化泛型类型:

var commandFlow = Activator.CreateInstance(flowType, new object[] {new StaticFlow()});

I get the error: 我得到错误:

"Constructor on type 'CommandFlow`1[[DynamicFlow, ...]]' not found" “找不到类型'CommandFlow`1 [[DynamicFlow,...]]'的构造函数”

The error indicates that you are trying to construct an object of type CommandFlow<DynamicFlow> , so nominalFlowType must have been DynamicFlow . 该错误表明您正在尝试构造CommandFlow<DynamicFlow>类型的对象,因此nominalFlowType必须为DynamicFlow

As you're trying to pass a StaticFlow as a constructor argument, there isn't any constructor that can do this; 当您尝试将StaticFlow作为构造函数参数传递时,没有任何构造函数可以做到这一点。 you'd need to pass a DynamicFlow value. 您需要传递DynamicFlow值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM