我在 class 中创建了一个包含诸如表单、按钮等的类。然后我在课堂上创建它们的句柄事件。看看下面我的类代码:
public static class InputBox
{
static Form form = new Form();
static Label label = new Label();
static TextBox textBox = new TextBox();
static Button buttonOk = new Button();
static Button buttonCancel = new Button();
public static DialogResult Show(string title, string promptText, ref string value)
{
form.Text = title;
label.Text = promptText;
textBox.Text = value;
buttonOk.Text = "OK";
buttonCancel.Text = "Cancel";
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;
label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);
label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
buttonOk.Click += new EventHandler(buttonOk_Click); //this is the handle code
buttonCancel.Click += new EventHandler(buttonCancel_Click);//this is the handle code
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
static void buttonCancel_Click(object sender, EventArgs e)
{
form.Close();
}
static void buttonOk_Click(object sender, EventArgs e)
{
MessageBox.Show("If u click this, You Will Get many Messages as many as you call the class");
}
}
然后,我在自己的表单代码中这样称呼它:
string strbuffer; // Global Variable
InputBox.Show("Hi..?", "What Is Your Name?",ref strbuffer);
//do something...
InputBox.Show("Hi..?", "What Is Your Age?",ref strbuffer);
//do something
InputBox.Show("Hi..?", "How Many Cars do you have?",ref strbuffer);
//do something
如果我调用该类的次数与调用它的次数一样多,则旧处理程序将永远不会被释放,因此处理程序控制中的代码将与调用该类的次数一样多
我猜当类不再使用时变量不会被释放所以变量总是在你每次调用它时累积
解决这种情况的最佳方法是什么?