遵循DRY与WinForms MDI子窗口
本文关键字:窗口 MDI WinForms DRY 遵循 | 更新日期: 2023-09-27 18:06:11
所以我正在使用WinForms在c#中构建一个MDI应用程序。在这种情况下,我无法弄清楚如何遵循DRY。我在我的主菜单条中使用toolstripmenuitems打开新的MDI儿童。我重用了"NewChild"方法作为这些事件的事件处理程序。我尽量不为每个子窗口重复我自己,因为它们都遵循相同的实例化模式。
我已经研究过泛型和使用Type类,但它并没有真正让我得到我想要的。理想情况下,我只想说
// etc...
TypeOfForm = ConfigurationForm;
}
new TypeOfForm();
但我认为不存在这种丢失的语言结构。
public partial class MainForm : Form
{
private AboutForm aboutForm;
private ConfigurationForm configForm;
private ResultsForm resultForm;
private LogForm logForm;
private void NewChild(object sender, EventArgs e)
{
Form newForm;
if (sender == testConfigurationToolStripMenuItem)
{
if (configForm == null)
{
configForm = new ConfigurationForm();
}
newForm = configForm;
}
else if (sender == resultsToolStripMenuItem)
{
if (resultForm == null)
{
resultForm = new ResultsForm();
}
newForm = resultForm;
}
else if (sender == logToolStripMenuItem)
{
if (logForm == null)
{
logForm = new LogForm();
}
newForm = logForm;
}
else
{
return;
}
newForm.MdiParent = this;
newForm.Disposed += new EventHandler(ChildDisposed);
newForm.Show();
}
}
在这种情况下实现DRY的好方法是什么?
我会不惜一切代价避免检查类型。它确实使代码混乱。
你真的想为这个通用代码使用泛型:
// for multiple instance forms (and instantiating a "singleton" form)
private void AddNewChild<T>() where T: Form
{
T newForm = new T();
newForm.MdiParent = this;
newForm.Disposed += new EventHandler(ChildDisposed);
newForm.Show();
}
// for "singleton" forms
private void ActivateChild<T>() where T: Form
{
// off-the-cuff guess, this line may not work/compile
var child = this.MdiChildren.OfType<T>().FirstOrDefault();
if (child == null)
{
AddNewChild<T>();
}
else
{
child.Show();
}
}
// usage
logToolStripMenuItem.Click += (s,e) => ActivateChild<LogForm>();
testConfigurationToolStripMenuItem.Click += (s,e) => ActivateChild<ConfigurationForm>();
multipleInstanceFormMenuItem.Click += (s,e) => AddNewChild<FormX>();
...
我有个建议:
用toolstrip对象(或使用Tag属性)和它们匹配的表单或表单类型创建一个字典
// you can't use the UI controls before Init, you could use their Tags
// so this should be considered pseudo code
private Dictionary<string, Type> ToolstripForms = new Dictionary<string, Type>
{
{ testConfigurationToolStripMenuItem, typeof(ConfigurationForm) },
{ resultsToolStripMenuItem, typeof(ResultsForm) },
};
和NewForm方法中的
private void NewChild(object sender, EventArgs e)
{
Form newForm = null;
// some casting and exception handling would go well here
if (sender != null && ToolstripForms.ContainsKey(sender)) // or sender.Tag?
{
newForm = Activator.CreateInstance(ToolstripForms[sender]) as Form;
}
...
}
您可能需要一种方法来确定表单是否已经打开并关注它,而不是每次都打开一个新表单,但这取决于您。一种方法是使用一对对象作为该字典中的值—类型和现有实例,尽管其他方法可能看起来更好。