例如我有以下类(class)。
public class Level1
{
public int intprop;
public Level2 level2;
}
public class Level2
{
public string strprop;
public Level3 level3;
}
public class Level3
{
public float fltprop;
}
现在如果我得到fltprop,那么如何知道这个属性层次结构是这样的Level1.level2.level3.fltpro?
有没有办法通过反射知道属性位置的层次结构?
更新:
如果查看 Level1 到 Level3 类,您可以看到 fltprop 位于 Level1 => level2 => level3 => fltprop 中。
现在通过使用反射,如果我得到 fltprop 作为 PropertyInfo,那么我可以知道这个属性来自 Level1 => level2 => level3 吗?意味着获取 propertyinfo 然后我知道这个属性的根 level3 然后知道 level3 的根 level2 然后知道 level2 的根是 level1。
最佳答案
Is there any way in reflection to know the hierarchy of property location?
没有。没有。
当您读取属性(实际上它现在是一个字段)时,您只有一个值。没有关于您从中读取它的对象类型的信息可用。当您拥有对象本身(Level3
对象)时,编译器或运行时无法告诉您您从哪里获得该对象。也许您刚刚创建了一个 Level3
的新实例,或者您可能从另一个对象的属性中读取了它。您只知道这一点,而不是运行时。
编辑:
假设您将 fltprop
的 PropertyInfo
与 Level3
类型的对象一起传递给方法。该方法的所有信息是属性名称为fltprop
,来自Level3
类型。这不会告诉方法您传递给该方法的Level3
对象来自哪里。这也没有存储在 Level3
类型信息中。实际上,当你读取Level3
的类型信息时,无论你如何获取类型,都是一样的:
var type1 = level3Obj.GetType();
var type2 = level1Obj.level2.level3.GetType();
var type3 = typeof(Level3);
var type4 = fltpropPropertyInfo.ReflectedType;
Console.WriteLine( type1 == type2 ); // outputs 'true'
Console.WriteLine( type2 == type3 ); // also outputs 'true'
Console.WriteLine( type3 == type4 ); // also 'true'
关于c# - 如何知道 C# 中属性位置的层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15381143/