首页 > 解决方案 > 如何创建一个可以同时包含堆栈和列表的引用,而无需在 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>();   
     }
}     

标签: c#listcollectionsstack

解决方案


堆栈定义为

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,但我想你知道这一点。


推荐阅读