[英]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.