0

我有一个班级继承人:

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>(),但这是首选方法吗?可能有更好的方法吗?

4

2 回答 2

5

我怀疑你只是想让它成为一个带有约束的泛型方法,以确保类型参数是Vehicle或子类:

public static IEnumerable<T> FilterByColor<T>(this IEnumerable<T> source, 
    string color) where T : Vehicle
{
    return source.Where(q => q.Color == color);
}
于 2012-08-01T17:30:17.887 回答
3

您需要使其通用:

public static IEnumerable<T> FilterByColor(this IEnumerable<T> source, string color) where T : Vehicle
于 2012-08-01T17:30:37.777 回答