如何知道c#中属性位置的层次结构?

如何知道c#中属性位置的层次结构?,c#,reflection,C#,Reflection,例如,我有以下课程 public class Level1 { public int intprop; public Level2 level2; } public class Level2 { public string strprop; public Level3 level3; } public class Level3 { public float fltprop; } 现在如果我得到fltpro,那么如何知道这个属性层次结构是这样的L

例如,我有以下课程

public class Level1
{
    public int intprop;
    public Level2 level2;
}

public class Level2
{   
    public string strprop;
    public Level3 level3;
}

public class Level3
{
    public float fltprop;
}
现在如果我得到fltpro,那么如何知道这个属性层次结构是这样的Level1.level2.level3.fltpro

反射中是否有任何方法可以知道财产位置的层次结构

更新: 如果查看Level1到Level3类,可以看到fltprop驻留在Level1=>level2=>Level3=>fltprop内部

现在通过使用反射,如果我将fltprop作为PropertyInfo,那么我可以知道这个属性来自Level1=>level2=>level3吗?这意味着获取propertyinfo之后,我知道该属性的根级别3,然后知道level3的根级别2,然后知道level2的根级别1

反射中是否有任何方法可以知道财产位置的层次结构

不,没有

当您读取属性(实际上它现在是一个字段)时,您只有一个值。没有关于从中读取对象类型的信息。当您拥有对象本身(
Level3
object)时,编译器或运行时无法告诉您从何处获取该对象。可能您刚刚创建了一个新的
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'

一般来说:没有。你只有一个对象;该对象可以在许多不同的地方使用,或者可以从同一图形中的多个路由访问。表达类似内容的唯一方法是从表达式树开始,即
expression expr=x=>x.Level2.Level3.fltprop-如果您有,那么答案将变为“是”。如果您是对的,例如,通过使用反射,我正在遍历level1属性并查找属性fltprop。然后我通过propertyinfo.setvalue(…)设置值。然后我们可以看到这个值在从level1读取时被反映出来。那么,我们为什么不知道它是从哪里来的呢?