C#使用泛型打开表单?

时间:2014-03-19 14:32:02

标签: c# winforms generics

我有一个主菜单,其中包含许多项目,这些项目又会打开不同的表单。目前我执行以下操作来打开特定表单:

        if (canShowCustomerForm)
            new CustomerForm().ShowDialog(this);
        else
        {
            MessageBox.Show("You don't have enough rights to view this form.");
        }

有没有办法在类中移动此代码,然后传递表单类型和布尔参数,而不是为每个菜单项重复代码?

2 个答案:

答案 0 :(得分:4)

public static class FormHelper
{
    public static DisplayResult ShowForm<T>(IWin32Window owner, bool canShowForm)
        where T : Form, new()
    {
        if (canShowForm)
        {
            using (T form = new T())
            {
                return form.ShowDialog(owner);
            }
        }
        else
        {
            MessageBox.Show("You don't have enough rights to view this form.");
        }
    }
}

答案 1 :(得分:0)

不是一遍又一遍地编写相同的逻辑,而是将其提取到如下函数中:

void ShowFormIfAllowed<TForm>(bool allowed) where TForm : Form, new() {
      if (allowed) {
          using (var form = new TForm()) {
               form.ShowDialog(this);
          }
      }
      else {
            MessageBox.Show("You don't have enough rights to view this form.");
      }
 }

然后在您的菜单处理中,您可以将其称为:

ShowFormIfAllowed<CustomerForm>(canShowCustomerForm);