【问题标题】:How to get all properties of a class with generic type parameter如何使用泛型类型参数获取类的所有属性
【发布时间】:2018-12-05 15:37:35
【问题描述】:

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

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
{
}

【问题讨论】:

    标签: c# generics getproperties


    【解决方案1】:

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

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

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

    【讨论】:

    • 完美!正是我想要的。 :-)
    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    相关资源
    最近更新 更多