简体   繁体   English

如何创建包含特定类型的通用集合?

[英]How can I create a generic collection which contains a specific type?

In C# I would like to create a generic deck of cards. 在C#中,我想创建一个通用的卡片组。 Enabling me to eg Create a stack of cards, a queue of cards or any other collection of cards? 使我能够例如创建一堆卡片,一张卡片或任何其他卡片集合? Providing that this collection is a derived from IEnumerable. 假设此集合是从IEnumerable派生的。

public class Deck<T> where T : IEnumerable
{
    private T<ICard> __Cards;

    public Deck() : this(52){}

    public Deck(int cards)
    {
        __Cards = new T<Card>(cards);
    }
}

Some other class... calling 其他一些课......打电话

Deck<List> _Deck = new Deck<List>();

I get the following error: 我收到以下错误:

The type parameter 'T' cannot be used with type arguments

I think this is a case that would be better solved with inheritance 我认为这是一个可以通过继承更好地解决的案例

public abstract class Deck 
{
  public abstract ICard this[int index]
  {
    get;
    set;
  }

  protected void Create(int cardCount);
}

public sealed class DeckList : Deck
{
  private List<ICard> m_list;
  public override ICard this[int index] 
  {
    get { return m_list[index]; }
    set { m_list[index] = value; }
  }
  protected override void Create(int cards) 
  {
    m_list = new List<ICard>(cards);
  }
}

If you continue down the generic path I think you will ultimately find that you need a type with 2 generic parameters 如果你沿着通用路径继续下去,我想你最终会发现你需要一个带有2个通用参数的类型

  • The collection type 集合类型
  • The element type 元素类型

Example

public class Deck<TElement, TCollection> 
  where TCollection : IEnumerable<TElement>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个泛型方法来返回调用指定的特定类型? - How can I create a generic method to return a specific type specified by the call? 如何创建具有泛型类型的接口集合 - How to create a collection of interfaces that have a generic type 如何使用Linq创建包含集合的唯一集合 - How to use Linq to create unique Collection which contains a collection 如何使用反射来查找开放泛型类型上的哪个开放泛型参数实现泛型接口? - How can I use reflection to find which open generic argument on an open generic type implements a generic interface? 如何将Type变量发送到通用方法? - How can I send Type variable to the method which is generic? 如何在C#中收集类型为泛型的类型 - How make a collection of type which is generic type in c# 我可以在 c# 中创建一个泛型方法,该方法根据是否包含某个方法来接受类型吗? - Can I create a generic method in c# that accepts a type based on whether it contains a certain method or not? 如何测试类的实例是否是特定的泛型类型? - How can I test if a instance of a class is a specific generic type? 如何在通用版本的TryParse()中转换为特定类型? - How can I convert to a specific type in a generic version of TryParse()? WCF OperationContract - 我应该公开哪种通用集合类型? - WCF OperationContract - which generic collection type should I expose?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM