请参阅以下示例。当具有属性类型是具有泛型类型参数的类的属性时,无论泛型类型参数如何,如何列出所有这些属性?
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
{
}