打开通用表单

时间:2013-05-29 06:23:48

标签: c# generics typeof

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

这是我到目前为止所做的:

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);

但我有兴趣知道是否有可能像我在第一个代码片段中尝试的那样做,以及需要做些什么才能实现这一点。

1 个答案:

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

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