我有一个班级继承人:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyProject.Models;
using MyProject.Extensions;
namespace MyProject.Models
{
public abstract class Vehicle
{
public string Color { get; set; }
}
public class Car : Vehicle
{
public int Mileage { get; set; }
}
public class Boat : Vehicle
{
public int Displacement { get; set; }
}
}
namespace MyProject.Extensions
{
public static class VehicleExtensions
{
public static IEnumerable<Vehicle> FilterByColor(this IEnumerable<Vehicle> source, string color)
{
return source.Where(q => q.Color == color);
}
}
}
namespace MyProject.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
List<Car> cars = new List<Car>();
cars.Add(new Car() { Color = "white", Mileage = 10000 });
cars.Add(new Car() { Color = "black", Mileage = 20000 });
IEnumerable<Car> filtered = cars.FilterByColor("black");
// Compile error, can not cast IEnumerable<Vehicle> to IEnumerable<Car>
//.OfType<Car>() - only this helps. I`m looking for another ways
return View(filtered);
}
}
}
我想使用扩展方法IEnumerable<Car>
并从中获取IEnumerable<Car>
,但方法返回IEnumerable<Vehicle>
,因为它适用于所有派生类 - 编译错误。我知道解决此问题的唯一一种方法是添加 call .OfType<Car>()
,但这是首选方法吗?可能有更好的方法吗?