如何编写一个执行此代码的函数

时间:2011-02-08 19:47:35

标签: c# winforms mdiparent

我已经使用此代码在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作为字符串或其他内容发送;以及如何将其包含在代码中...... 我想要最终的代码......

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

您还必须指定:

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

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