C#多态性简单的问题 [英] C# polymorphism simple question

查看:164
本文介绍了C#多态性简单的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类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.

另外,我怎么能初始化y的新实例,从一定的X - 我想这样做:

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

推荐答案

对不起有几个问题在这里。

There are a couple of questions here.

第一:我能型老虎的对象赋给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> 没有添加的方法,因此,这保证是安全的。

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://博客。 msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

第二个问题:我怎么能初始化的新实例老虎,从某些动物?

Second question: "how could I initialize a new instance of Tiger, from a certain Animal?"

您不能。有问题的动物可能是瓢虫。你将如何从瓢虫的实例初始化一个新的老虎?这没有任何意义,所以我们不会让你这么做。如果你想写一个知道如何将任意动物进入老虎自己的特殊方法,你可以自由地这样做。但是,我们不知道该怎么做你。

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#多态性简单的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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