所以我有这三个按钮点击.
private void btn_OpenNotePad_Click(object sender, EventArgs e) { this.Hide(); Form2 forma_NotePad = new Form2(); forma_NotePad.ShowDialog(); this.Close(); } private void btn_OpenPaint_Click(object sender, EventArgs e) { this.Hide(); Form3 forma_Paint = new Form3(); forma_Paint.ShowDialog(); this.Close(); } private void btn_ContactAdmin_Click(object sender, EventArgs e) { this.Hide(); Form4 forma_ContactAdmin = new Form4(); forma_ContactAdmin.ShowDialog(); this.Close(); }
它们都非常相似,所以我想到可以为它们创建一种方法吗?就像是:
private void OpenForm(parameter1, parameter2) { this.Hide(); parameter1 parameter2 = new parameter1(); parameter2.ShowDialog(); this.Close(); }
所以我可以打电话给他们
OpenForm(parameter1,parameter2);
并使我的代码更短,更清洁.
当然,您可以在单独的方法中重构此功能:
private void btn_OpenNotePad_Click(object sender, EventArgs e) { Open(); } private void btn_OpenPaint_Click(object sender, EventArgs e) { Open (); } private void btn_ContactAdmin_Click(object sender, EventArgs e) { Open (); } private void Open () where TForm: Form, new() { this.Hide(); new TForm().ShowDialog(); this.Close(); }