1

我想要一种方法,只能发送要打开的表单类型,然后打开该表单。

这是我到目前为止所拥有的:

private void OpenForm(Type t)
{
    if (OpenedForm != null)
    {
        OpenedForm.Close();
    }
        IList list = (IList)Activator.CreateInstance(
        typeof(List<>).MakeGenericType(t));
        OpenedForm.MdiParent = this;
        OpenedForm.Show();
        OpenedForm.WindowState = FormWindowState.Maximized;
}

我知道我可以制作这样的方法:

private void OpenForm(Form frm)
{
    if (OpenedForm != null)
    {
       OpenedForm.Close();
    }
    OpenedForm = frm;
    OpenedForm.MdiParent = this;
    OpenedForm.Show();
    OpenedForm.WindowState = FormWindowState.Maximized;
}

然后简单地这样称呼它:

 Form newform = new TestForm();
 OpenForm(newform);

但是我很想知道是否可以像我在第一个代码片段中尝试的那样做,以及需要做些什么来完成它。

4

1 回答 1

2
private void OpenForm(Type t)
{
    if(!typeof(Form).IsAssignableFrom(t))
        throw new ArgumentException("Required description of Form Type", "t");

    if (OpenedForm != null)
       OpenedForm.Dispose(); //will also close a Form

    OpenedForm = (Form)Activator.CreateInstance(t);
    OpenedForm.Show();
    OpenedForm.WindowState = FormWindowState.Maximized;
}

现在您只能传递类的Type元数据Form或其派生的元数据。所以如果你这样做:

OpenForm(typeof(Form));

将创建并打开一个新的空表单

于 2013-05-29T06:28:33.877 回答