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

查看:116
本文介绍了逻辑及其对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();

因此,从这一点到其逻辑结论,一组People也将是一组对象:

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?

对于记录,我相信我想要这种行为的情况是一个通用的打印功能,显示列表

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.

Eric Lippert有一个非常好的解释这个问题(它在十一部分或某事,会弯曲你的头脑在地方,但它是非常值得读)。请参阅此处

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.

挖掘出另一个相关链接, 。请参见此处

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

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

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