2008-10-14 151 views
2

我需要访问一些标记为内部的成员,这些成员在第三方程序集中声明。从反射属性中检索反射类型中的值

我想从一个类的特定内部属性返回一个值。然后我想从该返回值的属性中检索一个值。但是,这些属性返回也是内部的类型,并在此第三方程序集中声明。

这样做的例子我见过很简单,只是显示返回int或bool。有人可以给一些例子代码来处理这个更复杂的情况吗?

回答

3

你只要不断挖掘在返回值(或的PropertyInfo的属性类型):

ü

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); 
    } 
} 
1

您始终可以将其作为对象进行检索,并对返回的类型使用反射来调用其方法并访问其属性。