繁体   English   中英

如何使用泛型类型参数获取类的所有属性

[英]How to get all properties of a class with generic type parameter

请参阅以下示例。 当具有属性类型是具有泛型类型参数的类的属性时,如何列出所有这些属性而不管泛型类型参数?

class Program
{
    public static VehicleCollection<Motorcycle> MotorcycleCollection { get; set; }
    public static VehicleCollection<Car> CarCollection { get; set; }
    public static VehicleCollection<Bus> BusCollection { get; set; }

    static void Main(string[] args)
    {
        MotorcycleCollection = new VehicleCollection<Motorcycle>();
        CarCollection = new VehicleCollection<Car>();
        BusCollection = new VehicleCollection<Bus>();

        var allProperties = typeof(Program).GetProperties().ToList();
        Console.WriteLine(allProperties.Count);  // Returns "3".
        var vehicleProperties = typeof(Program).GetProperties().Where(p => 
            p.PropertyType == typeof(VehicleCollection<Vehicle>)).ToList();
        Console.WriteLine(vehicleProperties.Count);  // Returns "0".
        Console.ReadLine();
    }
}

public class VehicleCollection<T> where T : Vehicle
{
    List<T> Vehicles { get; } = new List<T>();
}

public abstract class Vehicle
{
}

public class Motorcycle : Vehicle
{
}

public class Car : Vehicle
{
}

public class Bus : Vehicle
{
}

您可以使用GetGenericTypeDefinition方法获取泛型类型的开放形式,然后将其与VehicleCollection<> (打开表单)进行比较,如下所示:

var vehicleProperties = typeof(Program).GetProperties()
    .Where(p =>
        p.PropertyType.IsGenericType &&
        p.PropertyType.GetGenericTypeDefinition() == typeof(VehicleCollection<>))
    .ToList();

IsGenericType用于确保属性类型是通用的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM