我有一个看起来像这样的类:
public class Parent
{
public class Subclass
{
}
}
Run Code Online (Sandbox Code Playgroud)
并使用反射我试图找到子类
void main
{
Parent p = new Parent();
Type t = p.GetType();
Type s = t.GetNestedType("Subclass"); //s is not set
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为显然没有嵌套类型。如何找到子类的类型?我需要获取 s 的原因是稍后调用 .GetMethod("someMethod").Invoke(...) 。
我只是尝试了完全相同的事情,它对我有用:
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());
}
Run Code Online (Sandbox Code Playgroud)
你确定 NestedClass 是公开的吗?