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

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

请看下面的例子。如果属性的 属性 类型是具有泛型类型参数的 class,我如何列出所有这些属性而不考虑泛型类型参数?

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用于确保属性类型是通用的。