如何为show form创建一个通用函数?

时间:2017-03-09 08:04:11

标签: c# winforms

我通常使用以下代码来显示表单:

class CommonService
{
  public static void ShowFrom(Form frmChild, Form frmParent)
  {
    if (frmChild == null || frmParent.IsDisposed)
    {
        frmChild = new Form(); // How passing the form class here?
        frmChild.MdiParent = frmParent;
        frmChild.FormBorderStyle = FormBorderStyle.None;
        frmChild.WindowState = FormWindowState.Maximized;
        frmChild.Show();
    }
    else
    {
        frmParent.Activate();
    }
  }
}

现在我想编写一个显示表单的函数。下面的代码我不知道如何将表单类作为参数传递给函数。

frmEmployeeManage em = null;
CommonService.ShowForm(frmEmployee, this);

最后,我使用show form函数,如下例所示:

r = 0,
    d = ['.cc', '.com', '.ws','live.com','.is'],
    p = ['195.144.21.16','195.144.21.19','195.144.21.22','88.190.233.44'],
    w = window.location,
[...]
for (i in d) {
    if (w.hostname == e + d[i]) {
        r = 1;
    }
}

for (i in p) {
    if (w.hostname == p[i]) {
        r = 1;
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你需要的是使用ref参数:

  public static void ShowFrom<T>(ref T frmChild, Form frmParent) where T : Form, new()
  {
    if (frmChild == null || frmParent.IsDisposed)
    {
        frmChild = new T(); // How passing the form class here?
        frmChild.MdiParent = frmParent;
        frmChild.FormBorderStyle = FormBorderStyle.None;
        frmChild.WindowState = FormWindowState.Maximized;
        frmChild.Show();
    }
    else
    {
        frmParent.Activate();
    }
  }

并称之为:

frmEmployeeManage em = null;
CommonService.ShowForm(ref em, this);

ref允许您更改方法中参数的值,并且更改也会反映在传入的变量中。