为什么不允许不同类型参数之间的转换?
我只是不明白,因为将一个通用容器转换为另一个通用容器会非常有用吗?
Stack <IType> stack = new Stack<SomeType>();
I just don't get it as it would be so useful to convert one generic container into the other?
Stack <IType> stack = new Stack<SomeType>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是在谈论这样的转换吗?
如果是这样,这就是所谓的协方差。 这通常与其对应的逆变配对。 目前的C#版本确实还没有这个功能。 但它将在 C# 和 VB.Net 的下一版本中提供。
有关即将发布的版本的一些文章
Are you talking about conversions like so?
If so, this is what is known as covariance. This is usually paired with it's counterpart contravariant. This feature is indeed not available in the current version of C#. But it will be available in next version of both C# and VB.Net.
Some articles about the upcoming release
虽然 @JaredPar 所说的是真的,但今天有一些针对集合的解决方法。 例如,如果存在从一种类型到另一种类型的合法转换,则可以使用 Cast IEnumerable 扩展。
或者您可以使用 Select 显式从一种类型转换为另一种类型。
请注意,这两种方法都会生成适当类型的新集合,而不是简单地将集合分配给不同类型的变量,这在 C#/VB 的下一版本中在某些条件下可用。
While what @JaredPar says is true, there are some work-arounds for collections that are available today. For instance, you can use the Cast IEnumerable extension if there is a legal cast from one type to another.
Or you could explicitly convert from one type to another using Select.
Note that both of these methods will produce a new collection of the appropriate type, not simply assign the collection to a variable of a different type as will be available under certain conditions in the next versions of C#/VB.
关于你给出的例子:
如果我们这样做会发生什么:
这是.Net中不允许协变的基本原因,我猜是因为泛型容器的底层集合不一定与声明的类型匹配。 Eric Lippert 的文章非常详细(超出了我的能力)。
With regard to the example you gave:
What would happen if we did this:
This is the basic reason why covariance is not allowed in .Net, I guess because the underlying collection for the generic container does not necessarily match the declared type. The articles by Eric Lippert go into great detail (more than I really can).