简体   繁体   English

如何从另一个表单通用地打开一个表单?

[英]how to generically open a form from another form?

I have a total of 6 forms. 我总共有6种表格。 In my mainForm, I have 5 buttons to open the other forms inside the panel. 在我的mainForm中,我有5个按钮可以打开面板中的其他表单。 what i know is something like this: 我所知道的是这样的:

 form1 f1 = new form1();
 f1.TopLevel = false;
 f1.Dock = DockStyle.Fill;
 this.panelMid.Controls.Add(f1);
 f1.show();

now, since I have 5 other forms, I want to make a function that would make me open the forms without re-typing those code in every button event. 现在,由于我还有其他5种形式,因此我想创建一个函数,使我可以打开表单而不必在每个按钮事件中重新键入这些代码。 My problem is that I don't know to pass the form into a function as parameter. 我的问题是我不知道将表单作为参数传递给函数。

DRY 101, based on your code, with some generics chucked in DRY 101,根据您的代码,加上了一些泛型

public void MyAwesomeFormShower<TForm>()
   where TForm : Form, new()
{
   var form = new TForm();
   // common code here
   form.TopLevel = false;
   form.Dock = DockStyle.Fill;
   ///this.panelMid.Controls.Add(f1); // < who knows what this does, however don't do it
   form.Show();
}

Usage 用法

MyAwesomeFormShower<MyLovelyHorseForm>();

Or if you want to get fancy 或者如果你想花哨

public void MyAwesomeFormShower<TForm>(Action<TForm> action = null) 
   where TForm : Form, new()   
{
   var form = new TForm();
   // common code here
   form.TopLevel = false;
   form.Dock = DockStyle.Fill;

   action?.Invoke();
   form.Show();
}

Usage 用法

MyAwesomeFormShower<MyLovelyHorseForm>();

// or

MyAwesomeFormShower<MyLovelyHorseForm>((form) => 
     {   
         // Specialised form stuff here
         // that is specific to MyLovelyHorseForm
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM