1

我已使用此代码在 MdiWindow 中制作和显示表单:

        if (currentForm != null) {
            currentForm.Dispose();
        }
        currentForm = new ManageCompanies();
        currentForm.MdiParent = this;
        currentForm.Show();
        currentForm.WindowState = FormWindowState.Maximized;

我用这段代码显示了大约 20 种不同的形式......

我想写一个这样的函数:

private void ShowForm(formClassName) {

            if (currentForm != null) {
                currentForm.Dispose();
            }
            currentForm = new formClassName();
            currentForm.MdiParent = this;
            currentForm.Show();
            currentForm.WindowState = FormWindowState.Maximized;
}

我是否必须将 formClassName 作为字符串或其他内容发送;以及如何将其包含在代码中...我想要最终代码...

4

2 回答 2

2

尝试泛型:

 public void ShowForm<FormClass>() where FormClass: Form,new() {

        if (currentForm != null) {
            currentForm.Dispose();
        }
        currentForm = new FormClass();
        currentForm.MdiParent = this;
        currentForm.Show();
        currentForm.WindowState = FormWindowState.Maximized;
}

或者使用反射

public void ShowForm(string formClassName) {

        if (currentForm != null) {
            currentForm.Dispose();
        }
        currentForm = (Form) Activator.CreateInstance(Type.GetType(formClassName)) ;
        currentForm.MdiParent = this;
        currentForm.Show();
        currentForm.WindowState = FormWindowState.Maximized;
}
于 2011-02-08T19:51:26.373 回答
0

您还必须指定:

private void ShowForm<FormClass> where T : Form, new() {

请注意那里的 new(),以便您可以默认构造 FormClass,否则它不会让您构造它。

于 2011-02-08T19:53:15.200 回答