我需要访问在第三方程序集中声明的一些标记为内部的成员。
我想从类中的特定内部属性返回一个值。然后我想从该返回值的属性中检索一个值。但是,这些属性返回的类型也是内部类型并在此第三方程序集中声明。
我见过的这样做的例子很简单,只是显示返回 int 或 bool。有人可以提供一些处理这个更复杂情况的示例代码吗?
最佳答案
您只需继续挖掘返回的值(或 PropertyInfo 的 PropertyType):
你
sing System;
using System.Reflection;
public class Foo
{
public Foo() {Bar = new Bar { Name = "abc"};}
internal Bar Bar {get;set;}
}
public class Bar
{
internal string Name {get;set;}
}
static class Program
{
static void Main()
{
object foo = new Foo();
PropertyInfo prop = foo.GetType().GetProperty(
"Bar", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
object bar = prop.GetValue(foo, null);
prop = bar.GetType().GetProperty(
"Name", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
object name = prop.GetValue(bar, null);
Console.WriteLine(name);
}
}
关于.net - 从反射属性中检索反射类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/200900/