为什么使用Linq时界面会丢失?

问题描述:

今天我发现了一些令人惊讶的东西,希望有人能向我解释发生了什么。看起来,Linq枚举可以干扰由对象实现的接口。如果你运行这段代码:为什么使用Linq时界面会丢失?

using System; 
using System.Collections.Generic; 
using System.Linq; 

public class Program 
{ 
    interface One 
    { 
     int id {get; set; } 
    } 

    class A : One 
    { 
     public int id {get; set; } 
    } 

    interface Two 
    { 
    } 

    class B : A, Two 
    { 
    } 

    public static void Main() 
    { 
     var list = new List<One>() { new B {id = 1} }; 

     var b1 = list.Where(x => x.id == 1); 
     var b2 = list.First(); 

     Console.WriteLine(b1 is Two); 
     Console.WriteLine(b2 is Two); 
    } 
} 

输出是:

False 
True 

我期待相同的对象由其中()和First()返回,但显然返回的对象有不同的类型。有人可以对此有所了解吗?

谢谢! - 汤姆B.

+7

'Where'' returns'IEnumerable ' – zerkms

+0

其中返回'IEnumerable '因为多个结果可以满足条件。 – mason

+1

var b1 = list.Single(x => x.id == 1); // console should print true – Derpy

.Where()将返回一个IEnumerable<One>,而不是One单个对象,因为条件可以通过多个所述List<One>内满足One对象。该方法.First()将检索可在IEnumerable<One>中找到所述第一One对象。