C#通用类类型参数(无法隐式转换)

编程入门 行业动态 更新时间:2024-10-20 00:29:31
本文介绍了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#通用类类型参数(无法隐式转换)

本文发布于:2023-11-11 23:18:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579816.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   类型   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!