c# - 如何创建一个可以同时包含堆栈和列表的引用,而无需在 c# 中进行强制转换?
问题描述
我希望能够引用超类中的集合,该集合需要在子类中包含堆栈或列表,但我无法理解如何使其工作,有什么想法吗?
就像是:
public class Group
{
Collection<Human> group;
}
public class PeopleStack : Group
{
public PeopleStack()
{
this.group = new Stack<Human>();
}
}
public class Crowd : Group
{
public Crowd()
{
this.group = new List<Human>();
}
}
解决方案
堆栈定义为
public class Stack<T> :
System.Collections.Generic.IEnumerable<T>,
System.Collections.Generic.IReadOnlyCollection<T>,
System.Collections.ICollection
列表是
public class List<T> :
System.Collections.Generic.ICollection<T>,
System.Collections.Generic.IEnumerable<T>,
System.Collections.Generic.IList<T>,
System.Collections.Generic.IReadOnlyCollection<T>,
System.Collections.Generic.IReadOnlyList<T>,
System.Collections.IList
因此,您可以使用其中一种强(通用)类型IEnumerable<Human>
或IReadOnlyCollection<Human>
for group
。
当然应该是这样protected
,但我想你知道这一点。
推荐阅读
- javascript - 使用 html 事件 onclick="function()" 的带有咖啡脚本的未定义方法
- ruby-on-rails - 具有多个条件的哈希数组中的 Ruby 搜索
- python - Tensorflow 和 Keras 之间 Adam 的不同学习曲线
- ruby-on-rails - 从关联循环中获取先前的结果
- javascript - 显示固定菜单滚动?
- c++ - 我正在尝试编写将 ASCII 转换为十进制、添加到它并转换回 ASCII 的软件
- java - 如何在 Android 中修复 SSLHandShakeException
- docker - 将 docker 容器中的 websocket 客户端连接到主机中的 websocket 服务器
- facebook - Facebook API 更改密码
- continuous-integration - 对某些语法发出警告