我想从特定类型中声明的类中检索属性,但不包括从基类型继承的类。如何通过反射查找类型的非继承属性
当然这是一个微不足道的例子,但我想提取最简单的代码。
真实案例的情况有点复杂,所以我并不想改变方法。
这里是我的代码:
class Program
{
static void Main(string[] args)
{
MyVehicles vehicles = new MyVehicles();
Type objectToInspectType = vehicles.GetType();
PropertyInfo[] propertyInfos = objectToInspectType.GetProperties();
foreach (PropertyInfo item in propertyInfos)
{
Console.WriteLine(item.PropertyType.Name); // Return Vehicle, Vehicle instead of Car, Car
}
Console.ReadKey();
}
}
public class Vehicle
{
public Vehicle()
{
WheelCount = 4;
}
public int WheelCount { get; set; }
}
public class Car : Vehicle
{
public Car()
{
Color = 10;
}
public int Color { get; set; }
}
public class MyVehicles
{
public MyVehicles()
{
vehicle1 = new Car();
vehicle2 = new Car();
}
public Vehicle vehicle1 { get; set; }
public Vehicle vehicle2 { get; set; }
}
我想两个属性(汽车&汽车,而不是汽车&车辆)。
感谢
感谢您的回答,但我wan't什么是显示汽车和汽车,而不是车辆和车辆是这种情况:PropertyInfo [] propertyInfos = objectToInspectType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); – DominiqueRT
好吧,我根据你的意见更新了我的答案。干杯。 – Nico