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

标签 c# reflection

例如我有以下类(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 的新实例,或者您可能从另一个对象的属性中读取了它。您只知道这一点,而不是运行时。

编辑:

假设您将 fltpropPropertyInfoLevel3 类型的对象一起传递给方法。该方法的所有信息是属性名称为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/

相关文章:

c# - WPF WebBrowser.Document 属性实际返回哪个对象?

c# - Winforms:当有垂直滚动条时,如何以编程方式显示 C# ListView 中的最后一项?

c# - DateTimePicker 数据绑定(bind)

c# - WMI 中的进程创建事件后读取附加信息出现延迟

pointers - 通过反射创建类型并通过引用传递可以编译但不起作用

Android P (API 28) - StrictMode 策略违规 "SmartSelectionEventTracker$SelectionEvent;->selectionAction"是什么意思?

c# - 字典 Getter 中的参数异常

java - 有没有办法从对象和类名初始化变量?(例如通过使用反射)

reflection - 如何动态测试 Self 类型和不相关的类型

c# - 任何人都知道一种快速获取枚举值自定义属性的方法吗?