我有一個類heirarсhy派生類的實例:擴展方法,它返回
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>
,因爲它的工作原理在所有派生類 - 編譯錯誤。我只知道解決這個問題的方法之一是添加電話.OfType<Car>()
,但這是一種首選方式嗎?可能有更好的方法嗎?
非常感謝你。 – Roman 2012-08-01 18:24:31