逻辑及其应用Collections.Generic和继承 [英] Logic and its application to Collections.Generic and inheritance

查看:181
本文介绍了逻辑及其应用Collections.Generic和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一切都继承自对象。它是在继承的基础。一切都可以隐式转换了继承树,即

Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie.

object me = new Person();

因此​​,通过其合乎逻辑的结论,在此之后,一群人也将是一组对象的:

Therefore, following this through to its logical conclusion, a group of People would also be a group of objects:

List<Person> people = new List<Person>();
people.Add(me);
people.Add(you);
List<object> things = people; // Ooops.

除,这是行不通的,是谁设计.NET的人要么忽略了这一点,或者是有原因的,我不知道哪个。至少有一次,我遇到了一个情况下,这将是有益的,但​​我一直在使用一个讨厌的黑客(子类名单只是为了实现一个转换运算符)结束了。

Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator).

现在的问题是这样的:有一个原因,这种行为?有没有一个简单的解决方案,以获得所需的行为吗?

The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour?

有关的记录,我相信,我想这种行为的情况是,通过调用toString()方法,并很好地格式化字符串显示的对象列表的通用打印功能。

For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely.

推荐答案

OK,大家谁在.NET中使用仿制药必须在一个点或另一个运行到这一点。

OK, everyone who has used generics in .net must have run into this at one point or another.

是的,直观的,它应该工作。不,在C#编译器的当前版本没有。

Yes, intuitively it should work. No, in the current version of the C# compiler it doesn't.

埃里克利珀有这个问题的一个很好的解释(这是十一个部分或者一些东西,会弯曲你的地方介意,但很值得读)。请参阅<一href="http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx"相对=nofollow>这里。

Eric Lippert has a really good explanation of this issue (it's in eleven parts or something and will bend you mind in places, but it's well worth the read). See here.

挖出了另一个相关的链接,这一次讨论了Java处理这一点。请参见这里

dug out another relevant link, this one discusses how java handles this. See here

这篇关于逻辑及其应用Collections.Generic和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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