我需要访问一些标记为内部的成员,这些成员在第三方程序集中声明。

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

我见过这样做的例子很简单,只是显示返回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);
    }
}

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top