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 に答える