我有一个MDI form,其中一些子窗体需要在关闭前显示消息框,而其他窗体则可以在没有询问的情况下关闭。由于从子窗体的close event调用application.Exit()时出现问题,我处理父窗体的close event并检查它的触发位置。如果它是在需要消息框的窗体中触发的,我会调用它,否则只需关闭应用程序即可。所有这些都在下面的代码中实现:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
SEdit se = this.ActiveMdiChild as SEdit;
SoEdit soleEdit = this.ActiveControl as SoEdit;
UppEdit ue = this.ActiveControl as UpEdit;
MEdit mat = this.ActiveControl as MEdit;
LEdit lse = this.ActiveControl as LEdit;
CEdit cle = this.ActiveControl as CEdit;
if (se != null || soleEdit != null || ue != null || mat != null || lse != null || cle != null)
{
if (MessageBox.Show("Do you want to save before exit?", "Closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.Yes)
{
MessageBox.Show("To Do saved.", "Status",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}我还在学习,但我知道这么长的if语句是糟糕代码的标志,但我不知道如何改进它。处理这种情况的正确方法是什么?
发布于 2013-02-01 23:10:07
提取条件以分离方法:
private bool AnyChildAlive()
{
return (this.ActiveMdiChild is SEdit) ||
(this.ActiveControl is SoEdit) ||
...
(this.ActiveControl is CEdit);
}然后调用此方法(也使用保护条件以避免嵌套的if语句):
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!AnyChildAlive())
return;
if (MessageBox.Show("Do you want to save before exit?", "Closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) != DialogResult.Yes)
return;
MessageBox.Show("To Do saved.", "Status",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}发布于 2013-02-01 23:10:25
可能最好的方法是创建一个接口,如下所示:
public interface IFormActions {
bool AskBeforeClosing();
void SaveData();
}然后,为每个表单实现该接口,并在MainForm_FormClosing方法中执行以下操作:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
IFormActions se = this.ActiveControl as IFormActions;
if ((se != null) && se.AskBeforeClosing()) {
if (MessageBox.Show("Do you want to save before exit?", "Closing", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) {
se.SaveData();
MessageBox.Show("Saved", "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}由于这段代码的编写方式,您不必为所有表单实现接口,只需为那些您实际想要提出结束语的表单实现接口即可。
发布于 2013-02-01 23:09:57
为了让它看起来更吸引人或者是更好的重用,你可以考虑将你的验证转移到不同的方法上。
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (FormIsValid())
{
if (MessageBox.Show("Do you want to save before exit?", "Closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.Yes)
{
MessageBox.Show("To Do saved.", "Status",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}
private bool FormIsValid()
{
return
(this.ActiveMdiChild as SEdit) != null ||
(this.ActiveControl as SoEdit) != null ||
(this.ActiveControl as UpEdit) != null ||
(this.ActiveControl as MEdit) != null ||
(this.ActiveControl as LEdit) != null ||
(this.ActiveControl as CEdit) != null;
}https://stackoverflow.com/questions/14649104
复制相似问题