簡體   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