根据基类属性筛选派生类

本文关键字:派生 筛选 属性 基类 | 更新日期: 2023-09-27 18:16:15

我有两个类(Car/Truck)共享一个基类(Automobile)。我想根据Car和Truck的基类Automobile上的属性过滤它们的集合。下面的代码会导致一个错误:

Cannot implicitly convert type   
'System.Collections.Generic.List<Example.Program.Automobile>' to    
'System.Collections.Generic.List<Example.Program.Car>'
Program.cs    48  27  Example

是否有可能通过基类属性进行过滤,而不必将结果转换回相应的派生类?

class Program
{
    public class Automobile
    {
        public string Manufacturer { get; set; }
        public static  IEnumerable<Automobile> GetByManufacturer(IEnumerable<Automobile> items, string manufacturer)
        {
            return items.Where(o => o.Manufacturer == manufacturer);
        }
    }
    public class Car : Automobile
    {
        public int TrunkSize { get; set; }
    }
    public class Truck : Automobile
    {
        public int BedSize  { get; set; }
    }
    static void Main(string[] args)
    {
        var cars = new List<Car> 
        {
            new Car { Manufacturer = "Toyota", TrunkSize = 100 },
            new Car { Manufacturer = "Kia", TrunkSize = 70 }
        };
        var trucks = new List<Truck> 
        {
            new Truck { Manufacturer = "Toyota", BedSize = 400 },
            new Truck { Manufacturer = "Dodge", BedSize = 500 }
        };
        // Problem: Get a list of Type Car and a List of Tpye Truck, 
        // where each List contains only cars manufactured by Toyota
        var mfr =  "Toyota";
        List<Car> toyotaCars = Automobile.GetByManufacturer(cars, mfr).ToList();
        List<Car> toyotaTrucks = Automobile.GetByManufacturer(trucks, mfr).ToList();
        Console.WriteLine(toyotaCars.First().GetType().Name);
        Console.WriteLine(toyotaTrucks.First().GetType().Name);
    }
}

根据基类属性筛选派生类

您可以将定义更改为

public static IEnumerable<TAuto> GetByManufacturer(IEnumerable<TAuto> items, string manufacturer)
                    where TAuto : Automobile
{
    return items.Where(o => o.Manufacturer == manufacturer);
}

现在您正在返回IEnumerable<Automobile>,然后调用ToList将其转换为List<Automobile>,然后尝试将其转换为List<Car>,这是不合法的,因为列表可以包含Automobile s而不是Car s。

通过更改,您将返回一个IEnumerable<Car>,它可以完全转换为List<Car>

另外,第二个调用的返回类型应该是List<Truck>,而不是List<Car>:

List<Truck> toyotaTrucks = Automobile.GetByManufacturer(trucks, mfr).ToList();