.net - 从反射属性中检索反射类型的值

标签 .net reflection access-modifiers

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

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

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

相关文章:

c# - 循环中的高效反射

go - 在 golang 反射 FieldByName 中忽略大小写

java - 访问修饰符如何影响 Java 的性能?

c# - 我可以将 C# 扩展方法的可见性限制为同一程序集中的类吗?

c# - 与私有(private)访问修饰符相反

c# - 在 ASP.NET MVC 中使用路由映射到 ASMX 服务

c# - DataBindings 问题,请解释

c# - 如何向 ScintillaNet 添加新的语言设置?

c# - ClickOnce发布后找到 'Application Files'目录

reflection - 如何通过反射访问字段的值(Scala 2.8)