当我的类多次实现IEnumerable <T>时,为什么我不能使用LINQ to Objects?

Dar*_*ryl 7 c# ienumerable linq-to-objects

我有一个有趣的问题,一个类继承自实现IEnumerable的类,但我也希望该类为不同的类型实现IEnumerable.除了IEnumerable扩展方法之外,一切都有效,这意味着默认情况下我不能对对象执行任何LINQ,而不必先进行强制转换.有没有人有任何想法,除了不断铸造?

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

namespace LinqTesting
{
    public class Trucks<T> : Vehicles, IEnumerable<Truck>
    {    
        public Trucks()
        {    
            // Does Compile
            var a = ((IEnumerable<Truck>)this).FirstOrDefault();
            // Doesn't Compile, Linq.FirstOrDefault not found
            var b = this.FirstOrDefault();
        }    

        public new IEnumerator<Truck> GetEnumerator() { throw new NotImplementedException(); }
    }    

    public class Vehicles : IEnumerable<Vehicle>
    {    
        public IEnumerator<Vehicle> GetEnumerator() { throw new NotImplementedException(); }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
    }    

    public class Vehicle { }

    public class Truck : Vehicle { }
}     
Run Code Online (Sandbox Code Playgroud)

Jak*_*cki 7

将您的代码更改为:

public class Trucks : Vehicles<Truck>
{    
}    

public class Vehicles<T> : IEnumerable<T>
    where T : Vehicle
{    
}    

public class Vehicle { }

public class Truck : Vehicle { }
Run Code Online (Sandbox Code Playgroud)


dig*_*All 7

实际上你可以,但你不能利用泛型类型推断,因为你的类实现IEnumerable<T>了两种不同类型中的两种,编译器无法知道你想要使用哪种类型.

您可以指定它直接,例如:

var b = this.FirstOrDefault<Truck>();
Run Code Online (Sandbox Code Playgroud)