How to create a general collection that contains a specific type?

In C #, I would like to create a common deck of cards. Turning me on, for example, Create a stack of cards, a queue in cards, or any other collection of cards? If this collection is derived from 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 classes ... calling

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

I get the following error:

The type parameter 'T' cannot be used with type arguments
+3
source share
1 answer

I think this is a case that will be better resolved 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 the general path, I think you will eventually find that you need a type with 2 standard parameters

  • Collection Type
  • Item type

Example

public class Deck<TElement, TCollection> 
  where TCollection : IEnumerable<TElement>
+3
source

All Articles