继承(使用集合。常规) [英] Inheritance (Work with Collection.Generic)

查看:151
本文介绍了继承(使用集合。常规)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

class A : IHelp

class B : IHelp

然后我想做这样的事情:

Then I want to do such thing like:

List<A> alist = new List<A>();

List<IHelp> hList = (List<IHelp>) alist; // Error!!!

我是一个初学者程序员。我将非常感谢你的详细答复。感谢您的帮助!

I am a beginner programmer. I will be very grateful to you for detailed answer. Thanks for help!

推荐答案

你不能像这样做,因为它会违反原始列表的约束。假设这个工作就像你说的(它实际上给出一个错误,但假设它工作):

You cannot do a cast like this, because it will violate the constraints of the original list. Suppose this works like you said (it actually gives an error, but assume it works):

List<A> aList = new List<A>();
List<IHelp> hList = aList; // Compile error, but say it would have worked..

那么,你可以做: / p>

then, you could have done:

hList.add(new B()); // WHAT??

这没有意义,因为你永远不能向原始列表中添加类型B的元素类型A.这就是为什么C#阻止你做你想要的作业。

This does not make sense, because you can never add an element of type B to the original list of type A. This is why C# prevents you from making the assignment you want.

这篇关于继承(使用集合。常规)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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