如何使generic <>此方法-> OpenForm()我不想为每种表单创建方法

时间:2019-11-14 19:09:00

标签: c#

UIDirector directorUI = new UIDirector();
UIActor actorUI = new UIActor();
private void directorToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenForm(directorUI);
}
private void actorToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenForm(actorUI);
}

void OpenForm(Form frm)
{
    if (frm.IsDisposed)
    {
        frm = new UIDirector();
    }
    frm.Show();
    frm.MdiParent = this;
}

2 个答案:

答案 0 :(得分:0)

我刚意识到你在问什么,并决定创建一个新答案。

为其扩展方法。

public static class UIExtensions
{
  public static void Present(this Form form, Form parent)
  {
    form.MdiParent = parent;
    form.Show();
  }
}

然后您可以actorUI.Present(this);

答案 1 :(得分:-1)

您可以使用new通用约束通过无参数构造函数创建特定对象。

UIDirector directorUI = new UIDirector();
UIActor actorUI = new UIActor();
private void directorToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenForm(directorUI);
}
private void actorToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenForm(actorUI);
}

void OpenForm<T>(T frm) where T: Form, new()
{
    if (frm.IsDisposed)
    {
        frm = new T();
    }
    frm.Show();
    frm.MdiParent = this;
}