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

发布于 2024-07-06 11:47:58 字数 189 浏览 10 评论 0原文

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

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

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

I need to access some members marked internal that are declared in a third party assembly.

I would like to return a value from a particular internal property in a class. Then I'd like to retrieve a value from a property on that returned value. However, these properties return types that are also internal and declared in this third party assembly.

The examples of doing this I've seen are simple and just show returning int or bool. Can someone please give some example code that handles this more complex case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

虚拟世界 2024-07-13 11:47:58

您只需继续挖掘返回的值(或 PropertyInfo 的 PropertyType):

u

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

You just keep digging on the returned value (or the PropertyType of the PropertyInfo):

u

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);
    }
}
我恋#小黄人 2024-07-13 11:47:58

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

You can always retrieve it as an object and use reflection on the returned type to invoke its methods and access its properties.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文