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

C# 如何使用泛型类型参数获取类的所有属性,c#,generics,getproperties,C#,Generics,Getproperties,请参见下面的示例。当属性类型为带有泛型类型参数的类时,如何列出所有这些属性而不考虑泛型类型参数 class Program { public static VehicleCollection<Motorcycle> MotorcycleCollection { get; set; } public static VehicleCollection<Car> CarCollection { get; set; } public static Vehi

请参见下面的示例。当属性类型为带有泛型类型参数的类时,如何列出所有这些属性而不考虑泛型类型参数

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
{
}
类程序
{
公共静态车辆收集摩托车收集{get;set;}
公共静态车辆收集车收集{get;set;}
公共静态车辆收集总线收集{get;set;}
静态void Main(字符串[]参数)
{
摩托车收集=新车收集();
CarCollection=新车采集();
总线收集=新车辆收集();
var allProperties=typeof(Program).GetProperties().ToList();
Console.WriteLine(allProperties.Count);//返回“3”。
var vehicleProperties=typeof(Program).GetProperties()。其中(p=>
p、 PropertyType==typeof(VehicleCollection)).ToList();
Console.WriteLine(vehicleProperties.Count);//返回“0”。
Console.ReadLine();
}
}
公共类车辆集合,其中T:车辆
{
列出车辆{get;}=new List();
}
公共抽象类车辆
{
}
公营电单车
{
}
公营车辆
{
}
公共巴士:车辆
{
}

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

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

IsGenericType
用于确保属性类型为泛型。

完美!正是我想要的。:-)