在C#中创建动态<T>

Deb*_*yay 3 c# c#-4.0

我需要使用界面创建Dynamic T. 但我收到"Type Casting"错误.这是我的代码:

interface IEditor { }

class Editor : IEditor { }

class Test<T> { }
Run Code Online (Sandbox Code Playgroud)

现在这将是动态的,所以我使用下面的代码:

Test<IEditor> lstTest = (Test<IEditor>)Activator.CreateInstance(typeof(Test<>).MakeGenericType(typeof(Editor)));
Run Code Online (Sandbox Code Playgroud)

我收到了以下错误

无法转换类型为"CSharp_T.Test"1 [CSharp_T.Editor]'的对象以键入"CSharp_T.Test"1 [CSharp_T.IEditor]'.

此错误不是编译错误,但我得到运行时错误.

das*_*ght 6

通用类不支持协方差,但接口支持协方差.如果你定义一个接口ITest<>并标记Tout参数,像这样,

interface IEditor { }

class Editor : IEditor { }

interface ITest<out T> { }

class Test<T> : ITest<T> { }
Run Code Online (Sandbox Code Playgroud)

你将能够做到这一点:

ITest<IEditor> lstTest = (ITest<IEditor>)Activator
    .CreateInstance(typeof(Test<>)
    .MakeGenericType(typeof(Editor)));
Run Code Online (Sandbox Code Playgroud)

但是,这会限制T参数在内部ITest<>及其实现中的使用方式.

在ideone上演示.