Get private property of a private property using reflection

别来无恙 提交于 2020-08-26 21:03:02

问题


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

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

If I've got something like the above and I have a reference to Foo, how can I use reflection to get the value Str out Foo's FooBar? I know there's no actual reason to ever do something like this (or very very few ways), but I figure there has to be a way to do it and I can't figure out how to accomplish it.

edited because I asked the wrong question in the body that differs from the correct question in the title


回答1:


You can use the GetProperty method along with the NonPublic and Instance binding flags.

Assuming you have an instance of Foo, f:

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

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

Update:

If you want to access the Str property, just do the same thing on the bar object that's retrieved:

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

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

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



回答2:


I'm not sure whether there is a practical difference, but there is a way to slightly simplify Andrew's answer.

Replace the call to GetGetMethod() with 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);


来源:https://stackoverflow.com/questions/30763207/get-private-property-of-a-private-property-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!