Reflection to find nested class?

2019-07-11 20:36发布

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
}

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.

标签: c# reflection
1条回答
Juvenile、少年°
2楼-- · 2019-07-11 21:16

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

Are you sure the NestedClass is public?

查看更多
登录 后发表回答