【问题标题】:Retrieving values in reflected types from reflected properties从反射属性中检索反射类型中的值
【发布时间】:2010-09-17 02:03:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: .net reflection access-modifiers


    【解决方案1】:

    您只需继续挖掘返回的值(或 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-10
        • 1970-01-01
        • 1970-01-01
        • 2017-01-19
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 2011-07-12
        相关资源
        最近更新 更多