创建并显示WinForm

时间:2015-04-01 14:38:01

标签: c# forms activator

我正在尝试使用通用方法在VS 2013中创建和显示表单,这是我的方法:

void showOrUpdateForm<T>(ref Form form) where T : Form 
{
    if (form == null)
    {
        form = Activator.CreateInstance(typeof(T)) as T;
        form.Show();
    }
    else
        form.WindowState = FormWindowState.Normal;

    form.Focus();
}

这段代码我是从这里得到的。所以当我尝试像他们这样说的那样调用这个方法时:

 myForm1 form;
 showOrUpdateForm<myForm1>(ref form);

它给我错误:

错误1'GestionEAS.GestionEAS.showOrUpdateForm(ref System.Windows.Forms.Form)'的最佳重载方法匹配有一些无效的参数

错误2参数1:无法从'ref package.Views.form'转换为'ref System.Windows.Forms.Form'

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

您无法将myForm1作为ref Form传递 您应该将其更改为ref T,以便参数类型与变量匹配。

此外,您应该将, new()添加到通用约束中,并将Activator.CreateInstance(typeof(T)) as T替换为new T()

答案 1 :(得分:0)

似乎,你想要这样的东西:

// I'd rather return potentially created form directly (not via "ref")
// do you need "this" in the method? That's why "static"
static T showOrUpdateForm<T>(T form = null)
  where T: Form, new() {

  if (null == form) 
    form = new T(); // <- no Activator since "new()" constraint is declared

  form.WindowState = FormWindowState.Normal;
  form.BringToFront(); // <- if the form is not a foreground one

  if (form.CanFocus) // <- better check than have an exception
    form.Focus();

  return form;
}
...
// more compact and readable
myForm1 form = showOrUpdateForm<myForm1>();

答案 2 :(得分:0)

如何做到这一点,将很好地满足创建具有不同参数的表单

void showOrUpdateForm<T>(ref T form, Func<T> formCreator) where T : Form 
{
    if (form == null)
    {
        form = formCreator();
        form.Show();
    }
    else
        form.WindowState = FormWindowState.Normal;
    if(form.CanFocus)
        form.Focus();
}

用它作为。 。

MyForm myForm = null;
form1 = showOrUpdateForm(myForm, () => new MyForm());