gpt4 book ai didi

c# - 如何使用泛型类型参数获取类的所有属性

转载 作者:太空宇宙 更新时间:2023-11-03 22:38:36 24 4
gpt4 key购买 nike

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

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用于确保属性类型是通用的。

关于c# - 如何使用泛型类型参数获取类的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53635785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com