问题描述
我有一个 X 类和一个 Y 类,后者派生自 X:
I got a class X and a class Y, the latter which derives from X :
class x {}
class y : x {}
然后我在某处使用 X 列表:
Then somewhere I am using a list of X :
List<X> lstX;
...
然后我想从我的另一个列表中的数据中使用一个新的 Y 列表...类似这些:
Then I'd like to use a new list of Y, from the data in my other list...something along those lines :
List<Y> lstY = lstX;
我相信 X 列表中的项目会自动转换为 Y,但事实并非如此.
I would believe that the items in the list of X would get converted automatically into Y, but thats not the case.
另外,我如何从某个 X 初始化 Y 的新实例?我想做:
Also, how could I initialize a new instance of Y, from a certain X? I would like to do :
var newX = new X();
var newY = new Y(X);
但它似乎并不像那样工作.
but it does not seem to work like that.
感谢您的帮助!抱歉格式化,尽力而为
Thanks for your help! and sorry for formatting, trying my best
推荐答案
这里有几个问题.
第一:我可以将 Tiger 类型的对象分配给 Animal 类型的变量.为什么我不能将 Tiger List 类型的对象分配给 List of Animal 类型的变量?"
First: "I can assign an object of type Tiger to a variable of type Animal. Why can I not assign an object of type List of Tiger to a variable of type List of Animal?"
因为这样会发生:
List<Tiger> tigers = new List<Tiger>();
List<Animal> animals = tigers; // this is illegal because if we allow it...
animals.Add(new Giraffe()); // ... then you just put a giraffe into a list of tigers.
在 C# 4 中这样做是合法的:
In C# 4 it will be legal to do this:
IEnumerable<Tiger> tigers = new List<Tiger>();
IEnumerable<Animal> animals = tigers;
这是合法的,因为 IEnumerable<T>
没有Add"方法,因此保证安全.
This is legal because IEnumerable<T>
has no "Add" method and therefore this is guaranteed to be safe.
有关 C# 4 的这一新特性的详细信息,请参阅我关于协方差的系列文章.
See my series of articles on covariance for details about this new feature of C# 4.
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
第二个问题:我怎样才能从某个 Animal 初始化一个新的 Tiger 实例?"
Second question: "how could I initialize a new instance of Tiger, from a certain Animal?"
你不能.有问题的动物可能是瓢虫.你将如何从 Ladybug 的实例初始化一个新的 Tiger?这没有任何意义,所以我们不让你这样做.如果您想编写自己的特殊方法,知道如何将任意动物变成老虎,您可以自由地这样做.但我们不知道如何为您做到这一点.
You cannot. The Animal in question could be a Ladybug. How are you going to initialize a new Tiger from an instance of Ladybug? That doesn't make any sense, so we don't let you do it. If you want to write your own special method that knows how to turn arbitrary animals into tigers, you are free to do so. But we don't know how to do that for you.
这篇关于C#多态简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!