大多数 .net 程序员的做法是:
- 将所有代码留在里面
MainForm.cs
,但声明一个新方法来分离执行清除的代码。
我总是留在事件处理程序方法(双击按钮时VS生成的那个)代码来更改鼠标光标(以防我调用的代码需要几秒钟或更长时间才能运行)并捕获所有未处理的异常,并将我的逻辑放在一个单独的私有方法中:
partial class MainForm : Form // this is MainForm.cs
{
// This is the method VS generates when you double-click the button
private void clearButton_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
ClearForm();
}
catch(Exception ex)
{
// ... have here code to log the exception to a file
// and/or showing a message box to the user
}
finally
{
this.Cursor = Cursors.Default;
}
}
private void ClearForm()
{
// clear all your controls here
myTextBox.Clear();
myComboBox.SelectedIndex = 0;
// etc...
}
}
在我看来,如果你想在 .net 中遵循传统的做事方式,你应该坚持第一个例子。
当代码不属于表单逻辑(例如数据访问代码或业务逻辑)时,建议将代码移出表单 .cs 文件。在这种情况下,我认为清除表单控件不符合业务逻辑。它只是表单代码的一部分,应该保留在MainForm.cs
.
但是如果你真的想把ClearForm
方法放在另一个 .cs 文件中,你可以创建一个新类并将ClearForm
方法移到那里。您还需要将每个控件的 Modifiers 属性更改为 Public,以便您的新类可以从 MainForm 外部访问它们。像这样的东西:
public class FormCleaner // this is FormCleaner.cs
{
public void ClearForm(MainForm form)
{
// clear all your controls here
form.myTextBox.Clear();
form.myComboBox.SelectedIndex = 0;
// etc...
}
}
您必须将主表单代码更改为:
partial class MainForm : Form // this is MainForm.cs
{
// This is the method VS generates when you double-click the button
private void clearButton_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
FormCleaner cleaner = new FormCleaner();
cleaner.ClearForm(this);
}
catch(Exception ex)
{
// ... have here code to log the exception to a file
// and/or showing a message box to the user
}
finally
{
this.Cursor = Cursors.Default;
}
}
}
但是请注意,您的FormCleaner
班级必须了解您的MainForm
班级才能知道如何清除表单的每个控件,或者您需要提出一个通用算法,该算法能够遍历Controls
任何表单的集合以清理它们:
public class FormCleaner // this is FormCleaner.cs
{
// 'generic' form cleaner
public void ClearForm(Form form)
{
foreach(Control control on form.Controls)
{
// this will probably not work ok, because also
// static controls like Labels will have their text removed.
control.Text = "";
}
}
}
正如其他人所说,MainForm.Designer.cs
它是机器生成的,你永远不应该把自己的代码放在那里。