使用反射获取私有 属性 的私有 属性

Get private property of a private property using reflection

public class Foo
{
    private Bar FooBar {get;set;}

    private class Bar
    {
        private string Str {get;set;}
        public Bar() {Str = "some value";}
    }
 }

如果我有类似上面的内容并且我有对 Foo 的引用,我如何使用反射从 Foo 的 FooBar 中获取值 Str?我知道没有真正的理由去做这样的事情(或者很少有方法),但我认为必须有一种方法来做到这一点,但我不知道如何完成它。

已编辑,因为我在 body 中问错了问题,与标题中的正确问题不同

您可以将 GetProperty methodNonPublicInstance 绑定标志一起使用。

假设您有一个 Foo 的实例,f:

PropertyInfo prop =
    typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);

MethodInfo getter = prop.GetGetMethod(nonPublic: true);
object bar = getter.Invoke(f, null);

更新:

如果您想访问 Str 属性,只需对检索到的 bar 对象执行相同的操作即可:

PropertyInfo strProperty = 
    bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);

MethodInfo strGetter = strProperty.GetGetMethod(nonPublic: true);

string val = (string)strGetter.Invoke(bar, null);

有一种方法可以稍微简化

将对 GetGetMethod() + Invoke() 的调用替换为对 GetValue() 的单个调用:

PropertyInfo barGetter =
    typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);
object bar = barGetter.GetValue(f);

PropertyInfo strGetter =
    bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);
string val = (string)strGetter.GetValue(bar);

我做了一些测试,没发现有什么不同,然后我发现this answer,它说GetValue()调用GetGetMethod()有错误检查,所以没有实际差异(除非你担心性能,但使用反射时我猜你不会)。