在C#中创建动态<t> </t>

时间:2013-09-20 20:02:40

标签: c# c#-4.0

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

interface IEditor { }

class Editor : IEditor { }

class Test<T> { }

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

Test<IEditor> lstTest = (Test<IEditor>)Activator.CreateInstance(typeof(Test<>).MakeGenericType(typeof(Editor)));

我收到以下错误

  

无法将“CSharp_T.Test`1 [CSharp_T.Editor]'类型的对象强制转换为'CSharp_T.Test`1 [CSharp_T.IEditor]'。

此错误不是编译错误,但我遇到运行时错误。

2 个答案:

答案 0 :(得分:6)

通用类不支持协方差,但接口支持协方差。如果您定义了一个界面ITest<>并将T标记为out参数,就像这样,

interface IEditor { }

class Editor : IEditor { }

interface ITest<out T> { }

class Test<T> : ITest<T> { }

你将能够做到这一点:

ITest<IEditor> lstTest = (ITest<IEditor>)Activator
    .CreateInstance(typeof(Test<>)
    .MakeGenericType(typeof(Editor)));

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

Demo on ideone

答案 1 :(得分:1)

Test不是协变的(它在通用参数中是不变的)。因此,Test<IEditor>不是Test<IEditor>的子类型。这两种类型之间没有关系。

您可以创建一个Test<IEditor>类型的对象,而不是Test<IEditor>,然后转换就可以成功。