我刚刚启动Project Euler,我已经遇到了第一个问题.我想为每个欧拉问题都有一个单独的表格,但我无法弄清楚如何以一种好的方式打开表格.我想要做的是使用变量problemNumber打开一个表单.例如,如果我将problemNumber设置为54并按下按钮,则应打开form54.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int problemNumber = int.Parse(numericUpDown1.Text);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道如何打开一个特定的表单,例如form2.
form2 f2 = new form2();
f2.Show();
Run Code Online (Sandbox Code Playgroud)
这将打开form2,但如上所述,我想打开表单+ problemNumber.
谢谢!
一种可能性是创建一个静态类,它有一个带有 switch case 的静态方法并返回一个Form对象。在该方法中,您创建关于指定数字的新表单对象:
public static class FormStarter
{
public static Form OpenForm(int formNumber)
{
Form form = null;
switch (formNumber)
{
case 1: form = new Form1(); break;
case 2: form = new Form2(); break;
//case 3: form = new Form3(); break;
// ...
default: throw new ArgumentException();
}
return form;
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以像这样使用该类:
var f = FormStarter.OpenForm(2);
f.ShowDialog(); // Form2 is started!
Run Code Online (Sandbox Code Playgroud)
一旦有了新表单,您只需使用一种方法添加实例的创建 - OpenForm.
没有静态类的另一种可能的解决方案是Dictionary保存数字和表单实例的对象,如下所示:
Dictionary<int, Form> forms = new Dictionary<int, Form>();
forms.Add(1, new Form1());
forms.Add(2, new Form2());
forms[2].ShowDialog(); // Form2 is started!
Run Code Online (Sandbox Code Playgroud)
如果您只想引用字典中表单的类型并仅在需要时创建实例,则将字典的值更改为 typeType并将相应的表单放入其中:
Dictionary<int, Type> forms = new Dictionary<int, Type>();
forms.Add(1, typeof(Form1));
forms.Add(2, typeof(Form2));
((Form)Activator.CreateInstance(forms[2])).ShowDialog(); // Form2 is started!
Run Code Online (Sandbox Code Playgroud)