【发布时间】:2014-02-14 09:16:03
【问题描述】:
假设我有以下课程:
public class Car
{
public Car()
{
}
}
public class Motor
{
public Motor()
{
}
}
public class Vehicle
{
public Vehicle()
{
SuperCar = new Car();
}
public Car SuperCar { get; set; }
public string TestName { get; set; }
}
让我们看看下面的代码:
Vehicle vehicle = new Vehicle();
Car superCar = vehicle.SuperCar;
现在,如果我们只给定 Car 实例,它是 superCar,是否有可能从反射中知道 superCar 实例实际上属于 Vehicle 的属性之一?
好的。谢谢你的cmets。我认为可以通过反射实现。
所以,如果我们扩展代码:
PropertyInfo[] props = vehicle.GetType().GetProperties();
提供,我们只得到:
PropertyInfo propInfo = props[0];
我们可以通过MemberInfo知道这个propInfo实际上属于哪个类:
Console.WriteLine(((System.Reflection.MemberInfo)(propInfo)).DeclaringType.Name);
它会返回 Vehicle。
谢谢!
【问题讨论】:
-
我认为您不需要对此进行反思。我想你只需要
if (superCar == vehicle.superCar) -
如果你只有一个
Car的实例,就没有办法从那里遍历属性到达Vehicle。因此,除非您已经从可以交叉引用的Vehicle列表开始,否则反射对您没有帮助。 -
问题是,你为什么要这么做?这不是精心设计的面向对象程序中需要的信息。
标签: c# .net reflection properties relationship