[英]How can I create a generic method to return a specific type specified by the call?
[英]How can I create a generic collection which contains a specific type?
在C#中,我想創建一個通用的卡片組。 使我能夠例如創建一堆卡片,一張卡片或任何其他卡片集合? 假設此集合是從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);
}
}
其他一些課......打電話
Deck<List> _Deck = new Deck<List>();
我收到以下錯誤:
The type parameter 'T' cannot be used with type arguments
我認為這是一個可以通過繼承更好地解決的案例
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);
}
}
如果你沿着通用路徑繼續下去,我想你最終會發現你需要一個帶有2個通用參數的類型
例
public class Deck<TElement, TCollection>
where TCollection : IEnumerable<TElement>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.