Как получить все свойства класса с параметром универсального типа - PullRequest
0 голосов
/ 05 декабря 2018

См. Следующий пример.При наличии свойств, где типом свойства является класс с параметром универсального типа, как я могу перечислить все эти свойства независимо от параметра универсального типа?

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

1 Ответ

0 голосов
/ 05 декабря 2018

Вы можете использовать метод GetGenericTypeDefinition, чтобы получить открытую форму универсального типа, а затем сравнить ее с VehicleCollection<> (открытая форма) следующим образом:

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

IsGenericType используетсячтобы убедиться, что тип свойства является общим.

...