发送List< T>的一些问题作为IEnumerable< T>一种方法 [英] Some issues with sending List<T> as IEnumerable<T> to a method

查看:146
本文介绍了发送List< 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>卡片{get;组; }
}

public class CardHolder:ICardHolder
{
private List< Card> cards = new List< Card>();
公共列表< Card>卡
{
获得{返回卡; }
set {cards = value; }
}

// ........
}

公共类甲板:ICardHolder
{
// .........

public void Deal(IEnumerable< ICardHolder> cardHolders)
{
// ........
}

// .........
}

公共类游戏
{
甲板甲板= new Deck();
清单< CardHolder> players = new List< CardHolder>();

// .........

deck.Deal(球员); //问题在这里!

// .........
}


List< T> 不是 IEnumerable< T1>的子类型 / code>即使 T:T1



C#中的泛型(C#4.0之前)是不变的(即没有这种子类型关系)。在.Net 4中, IEnumerable< T> 将其类型参数标注为协变。这意味着 List< T> 将是 IEnumerable< T1> 的子类型,如果 T :T1



请参阅 this page on the MSDN for this details of this feature。



编辑 - 您可以通过使用 Deal 方法泛型来解决此问题:

 <$ (IEnumerable< T> cardHolders)其中T:ICardHolder 
{
// ........
}


Possible Duplicate:
Upcasting and generic lists

Ok, I want to send a List<CardHolder> as an IEnumerable<ICardHolder> where CardHolder : ICardHolder. However, the compiler errors:

Error 4 Argument '1': cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'

This seems strange to me, considering that an List<T> : IEnumerable<T>. What's going wrong?

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!

    // .........
}

解决方案

The problem is that List<T> is not a subtype of IEnumerable<T1> even if T : T1.

Generics in C# (before C# 4.0) are 'invariant' (ie. don't have this sub-typing relationship). In .Net 4, IEnumerable<T> will have its type parameter annotated as being 'covariant'. This means that List<T> will be a subtype of IEnumerable<T1> if T : T1.

See this page on MSDN for more details of this feature.

Edit - You can work around this in your case by making the Deal method generic:

public void Deal<T>(IEnumerable<T> cardHolders) where T : ICardHolder
{
     // ........
}

这篇关于发送List&lt; T&gt;的一些问题作为IEnumerable&lt; T&gt;一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆