使用反射获取私有财产的私有财产 [英] 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?我知道没有真正的理由去做这样的事情(或很少有方法),但我认为必须有一种方法来做到这一点,但我不知道如何完成它.
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
推荐答案
您可以使用 GetProperty
方法以及 NonPublic
和 Instance
绑定标志.
You can use the GetProperty
method along with the NonPublic
and Instance
binding flags.
假设你有一个 Foo
的实例,f
:
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);
更新:
如果您想访问 Str
属性,只需对检索到的 bar
对象执行相同的操作:
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);
这篇关于使用反射获取私有财产的私有财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!