C#通用类类型参数(无法隐式转换) [英] C# Generic Class Type parameter (cannot implicitly convert)

查看:167
本文介绍了C#通用类类型参数(无法隐式转换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

class A { }

class B : A { }

class C<T> where T: A { }

问题

当B是A的子类时,为什么不能C<A> = C<B>? 会引发无法隐式转换"错误

Why cant C<A> = C<B> when B is a subclass of A? it throws the "cannot implicitly convert" error

谢谢

-更新- 我可以为C<A>创建可识别C<B>的隐式方法吗?

--UPDATE-- can i create an implicit method for that C<A> would recognize C<B>?

推荐答案

使用 co -variant (如果需要执行此操作),并且由于 co-variant 仅与接口和委托一起使用,因此请定义一个带有魔术词 out 而不是类:

Use co-variant if you need to do this, and because co-variant just work only with interface and delegate, so define an interface with the magic word out instead of class:

interface IC<out T> where T : A
{
}

因此,您可以根据需要分配:

So, you can assign like you want:

class CA : IC<A>
{}

class CB : IC<B>
{ }

IC<A> x = new CA();
IC<B> y = new CB();

x = y;

这篇关于C#通用类类型参数(无法隐式转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆