Reflection for finding a nested class?

I have a class that looks something like this:

public class Parent
{
    public class Subclass
    {
    }
}

and using reflection I'm trying to find a subclass

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

This does not work, because there are apparently no nested types. How to find the type of subclass? The reason I need to get s is to then call .GetMethod ("someMethod"). Call (...) on it.

+2
source share
1 answer

I just tried the 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 NestedClass is publicly available?

+3
source

Source: https://habr.com/ru/post/1672182/


All Articles