![](/img/trans.png)
[英]Get all properties of an inherited class in a function using generic type <T>
[英]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.