C#中的类和对象 [英] Clases and Objects in c#

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

问题描述

我有下一种情况

通用类:

public class A {
...
}

and two clases:

public class B: A {
...
}

public class C: A {
...
}

在代码的某些部分中,我想做类似的事情(列表之前已填充):

In some part of the code I want to do something like (list is filled previously):

foreach (A item in list) {
   listB.add((B) item);
}

是否可以做到?我只想将通用图标列表绑定到扩展通用类的分类列表。

Is it possible to do it? I just want to bind the list of generic ítems to the list of clases extends the generic class.

谢谢

推荐答案

您无法执行自己想做的事情,因为您无法将 C 类型的项目添加到列表中 B

You cannot do what you are trying to do because you won't be able to add items of type C to your list of B items

但是您可以

foreach(B item in list.OfType<B>())
       listB.add(item);

这篇关于C#中的类和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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