可能重复的一些问题:
Upcasting and generic lists与发送列表<T>为IEnumerable <T>的方法
好吧,我想送一个List<CardHolder>
为IEnumerable<ICardHolder>
其中CardHolder : ICardHolder
。然而,编译器错误:
错误4参数 '1':无法从 'System.Collections.Generic.List' 到 'System.Collections.Generic.IEnumerable' 转换
这似乎很奇怪对我来说,考虑一个List<T> : IEnumerable<T>
。出了什么问题?
public interface ICardHolder
{
List<Card> Cards { get; set; }
}
public class CardHolder : ICardHolder
{
private List<Card> cards = new List<Card>();
public List<Card> Cards
{
get { return cards; }
set { cards = value; }
}
// ........
}
public class Deck : ICardHolder
{
// .........
public void Deal(IEnumerable<ICardHolder> cardHolders)
{
// ........
}
// .........
}
public class Game
{
Deck deck = new Deck();
List<CardHolder> players = new List<CardHolder>();
// .........
deck.Deal(players); // Problem is here!
// .........
}
没有,所以我需要将我的列表转换为列表能够将它作为IEnumerable 发送?哦,是否有可能在VS2008上获得某种C#4.0的预览? –
2009-08-14 21:41:01
这里有一篇关于泛型中的co/contravariance的优秀InfoQ文章:http://www.infoq.com/news/2008/08/GenericVariance – 2009-08-14 21:41:39
+50泛型方法(如果可以的话)。谢谢! – 2009-08-14 21:50:35