3

我需要使用界面创建动态 T。但我收到“类型转换”错误。这是我的代码:

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]”类型。

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

4

2 回答 2

6

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

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<>及其实现。

ideone 上的演示

于 2013-09-20T20:15:10.943 回答
1

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

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

于 2013-09-20T20:09:29.140 回答