【发布时间】:2011-06-24 19:09:52
【问题描述】:
我有一个有趣的问题,即一个类继承自一个实现 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 { }
}
【问题讨论】:
-
你的 Truck 对象不是继承了两个 IEnumerable 类型吗?您如何期望编译器找出您要使用的可枚举类型,尝试向上转换为您想要的类型,然后选择 FirstOrDefault
标签: c# ienumerable linq-to-objects