使用反射获取私有财产的私有财产

cla*_*lol 7 c# reflection

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

    private class Bar
    {
        private string Str {get;set;}
        public Bar() {Str = "some value";}
    }
 }
Run Code Online (Sandbox Code Playgroud)

如果我有类似上面的内容并且我有一个Foo的引用,我怎么能用反射来获得价值Str out Foo的FooBar?我知道没有任何理由可以做这样的事情(或者很少的方式),但我认为必须有办法做到这一点,我无法弄清楚如何实现它.

编辑,因为我在正文中提出的错误问题与标题中的正确问题不同

And*_*ker 18

您可以将该GetProperty方法NonPublicInstance绑定标志一起使用.

假设你有一个实例Foo,f:

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

MethodInfo getter = prop.GetGetMethod(nonPublic: true);
object bar = getter.Invoke(f, null);
Run Code Online (Sandbox Code Playgroud)

更新:

如果要访问该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);
Run Code Online (Sandbox Code Playgroud)


Ark*_*ane 9

有一种方法可以稍微简化安德鲁的答案

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);
Run Code Online (Sandbox Code Playgroud)

我做了一些测试,没有发现差异,然后我找到了这个答案,它说GetValue()调用时GetGetMethod()进行错误检查,因此没有实际差异(除非您担心性能,但是当使用反射时,我猜您赢了't)。