我有一個有趣的問題,其中一個類從實現IEnumerable的類繼承,但我也希望該類爲不同類型實現IEnumerable。除IEnumerable擴展方法之外,一切都可以使用,這意味着默認情況下我不能對LINQ進行任何操作,而無需先執行任何操作。除了不斷鑄造,有沒有人有任何想法?當我的類多次實現IEnumerable <T>時,爲什麼我不能使用LINQ to Objects?
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 { }
}
是不是你的Truck對象繼承兩個IEnumerable類型?您如何期望編譯器找出您想要使用的枚舉類型,嘗試向上轉換爲您想要的類型,然後選擇FirstOrDefault –