加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中创建动态

发布时间:2020-12-16 01:57:17 所属栏目:百科 来源:网络整理
导读:我需要使用界面创建Dynamic T.但我收到“Type Casting”错误. 这是我的代码: interface IEditor { }class Editor : IEditor { }class TestT { } 现在这将是动态的,所以我使用下面的代码: TestIEditor lstTest = (TestIEditor)Activator.CreateInstance(typ
我需要使用界面创建Dynamic T.但我收到“Type Casting”错误.
这是我的代码:

interface IEditor { }

class Editor : IEditor { }

class Test<T> { }

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

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

我收到了以下错误

Unable to cast object of type ‘CSharp_T.Test`1[CSharp_T.Editor]’ to type ‘CSharp_T.Test`1[CSharp_T.IEditor]’.

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

解决方法

通用类不支持协方差,但接口支持协方差.如果您定义了一个接口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)));

然而,这将限制在ITest内部可以使用T参数的方式<>及其实施.

Demo on ideone.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读