代码之家  ›  专栏  ›  技术社区  ›  Steven

IEnumerable.ToArray与IEnumerable.Cast的比较

  •  4
  • Steven  · 技术社区  · 14 年前

    当试图从一个IEnumerable对象集合中获取一个对象数组(强制转换不同于我想要的数组)时,我知道我可以首先将源集合强制转换为正确的类型,然后从中获取一个数组,但是方法 ToArray<T>() 给我的印象是它可以一步完成这两个操作。但根据我的经验,我 从未 排列<T>() 方法对任何T都有效,除了原始源的T 很傻,因为它和非通用的 ToArray() 已经有了)。

    所以我的问题是,我是否遗漏了 排列<T>() 方法,我试图让它做一些它从来没有打算做的事情,或者有什么愚蠢的东西,我错过了关于方法,而我试图做的通常是遵循它的意图?

    下面是一个具体的例子来说明我的问题:

    public interface IFoo { }
    public class Foo : IFoo { }
    
    static void Main(string[] args)
    {
        // Suppose a list of Foos was created
        List<Foo> src = new List<Foo>();
    
        // I would be safe obtaining an array of IFoos from that list, but
    
        // This is not supported (although intellisense shows the method is there, the compiler balks):
        // IFoo[] results = src.ToArray<IFoo>();
    
        // Whereas this works just fine:
        IFoo[] results = src.Cast<IFoo>().ToArray();
    }
    
    1 回复  |  直到 14 年前
        1
  •  7
  •   cdhowie    14 年前

    原因 ToArray<T>() 是通用的,所以它可以在 任何 IEnumerable<T> T :

    public static T[] ToArray<T>(this IEnumerable<T> self) { ... }
    

    T型 你自己。如果您这样做了,如您的示例中所示,方法将期望接收 IEnumerable<IFoo> ,但你没有提供。

    T型