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

c# – 转换泛型和泛型类型

发布时间:2020-12-15 04:32:46 所属栏目:百科 来源:网络整理
导读:考虑一下,我有以下3个类/接口: class MyClassT { }interface IMyInterface { }class Derived : IMyInterface { } 我希望能够投射一个MyClass Derived进入MyClass IMyInterface或反之亦然: MyClassDerived a = new MyClassDerived();MyClassIMyInterface b
考虑一下,我有以下3个类/接口:
class MyClass<T> { }

interface IMyInterface { }

class Derived : IMyInterface { }

我希望能够投射一个MyClass< Derived>进入MyClass< IMyInterface>或反之亦然:

MyClass<Derived> a = new MyClass<Derived>();
MyClass<IMyInterface> b = (MyClass<IMyInterface>)a;

但是如果我尝试,我会遇到编译错误:

Cannot convert type 'MyClass<Derived>' to 'MyClass<IMyInterface>'

我确信有一个很好的理由我不能这样做,但我想不出一个.

至于为什么我想这样做 – 我想象的场景是你理想地想要使用MyClass< Derived>的实例的场景.为了避免许多讨厌的强制转换,你需要将你的实例传递给接受MyClass< IMyInterface>的接口.

所以我的问题是双重的:

>为什么我不能在这两种类型之间施放?
>有没有办法保持使用MyClass< Derived>实例的好处?同时仍然可以将其转换为MyClass< IMyInterface>?

解决方法

这不起作用,因为C#仅支持接口和委托的类型参数的协方差.如果你的类型参数仅存在于输出位置(即你只从类中返回它的实例而不接受它作为参数),你可以创建一个这样的接口:
interface IClass<out T> { }
class MyClass<T> : IClass<T> { }

这将允许你这样做:

IClass<Derived> a = new MyClass<Derived>();
IClass<IMyInterface> b = a;

老实说,这与你将要获得的一样接近,这需要C#4编译器才能工作.

(编辑:李大同)

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

    推荐文章
      热点阅读