反射找到嵌套类? [英] Reflection to find nested class?

查看:37
本文介绍了反射找到嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的类:

I've got a class that looks something like this:

public class Parent
{
    public class Subclass
    {
    }
}

并使用反射我试图找到子类

and using reflection I'm trying to find the subclass

void main
{
    Parent p = new Parent();
    Type t = p.GetType();
    Type s = t.GetNestedType("Subclass"); //s is not set
}

这不起作用,因为显然没有嵌套类型.如何找到子类的类型?我需要获取 s 的原因是稍后调用 .GetMethod("someMethod").Invoke(...) .

This doesn't work because there apparently are no nested types. How can I find the type of the subclass? The reason I need to get s is to later call .GetMethod("someMethod").Invoke(...) on it.

推荐答案

我刚刚尝试了完全相同的事情,它对我有用:

I just tried the exact same thing, and it worked for me:

    public class ParentClass
    {
        public class NestedClass
        {

        }
    }

       private void button1_Click(object sender, EventArgs e)
        {
            Type t = typeof(ParentClass);
            Type t2 = t.GetNestedType("NestedClass");
            MessageBox.Show(t2.ToString());
        }

您确定 NestedClass 是公开的吗?

Are you sure the NestedClass is public?

这篇关于反射找到嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆