打开新表格的类方法C#

时间:2019-02-15 15:40:10

标签: c# .net

我想知道下面是否有另一种方法可以在此方法中执行此代码,因为我在几乎所有表单中都使用不同的表单实例来调用此方法。 所以我需要创建如下代码:

public void NewForm(Form target)
...
target myform = new target();
target.Show();
...

并这样称呼:

NewForm(Form2);

2 个答案:

答案 0 :(得分:2)

我不知道这种方法有多有用,但是,您可以采用几种方法。

通用方法

定义:

void NewForm<T>()
  where T : Form, new()
{
  T instance = new T();
  instance.show();
}

调用:

NewForm<LayoutForm>();
  • 优点:
    • 在编译时进行类型检查
    • 安全
  • 缺点:
    • 不是您要求的格式。
    • 不允许传递参数。

类型自变量函数

定义:

void NewForm(Type formType)
{
    if(formType.IsSubclassOf(typeof(Form)))
    {
        var form = Activator.CreateInstance(formType) as Form;
        form.show();
    }
}

调用:

NewForm(LayoutForm);
  • 优点:
    • 您要求使用这种格式
  • 缺点:
    • 不允许将参数传递给构造函数。
    • 如果无法使用Activator.CreateInstance(x);创建类型,则抛出该异常
    • 运行时类型检查

传递表单实例

定义:

void NewForm(Form form)
{
  form.show();
}

调用:

NewForm(new LayoutForm());
  • 优点:
    • 允许传递参数。
    • 安全->在编译时检查类型。
  • 缺点:
    • 不是您要求的格式
    • 金达毫无意义。

答案 1 :(得分:0)

感谢Hans Passant的代码以及向我展示通用方法的其他人。我不知道这种通用方法。

Class.cs

public void NewForm<T>() where T:Form, new() 
{ 
T frm = new T(); ... 
frm.Show();
}

Form.cs

private void button1_Click_1(object sender, EventArgs e)
{
NewForm<Form2>();
}