我有一个 MDI 表格。如果另一个表单正在运行,我想在此表单的正在运行的子项中检查。就像是:
if (this.MdiParent.MdiChildren.Contains(MyForm2))
{
//Do Stuff
}
MyForm2
我要查找的表单的名称(类名)在哪里。编译器会说“此时类名无效”。
如何正确执行此操作?请注意,我可以在那个时刻运行多个“MyForm2”实例(嗯,使用不同的实例名称!)
只需创建一个循环来循环遍历 MdiChildren 集合,以查看是否存在任何形式的指定 Type。包含需要特定实例才能返回有效数据:
foreach (var form in this.MdiParent.MdiChildren)
{
if (form is MyForm2)
{
// Do something.
// If you only want to see if one instance of the form is running,
// add a break after doing something.
// If you want to do something with each instance of the form,
// just keep doing something in this loop.
}
}
您需要检查每个孩子的类型。
例如,您可以使用is
关键字(更多信息)来确定孩子是否是正确的类型:
if (this.MdiParent.MdiChildren.Any(child => child is MyForm2))
{
}
该.Any()
方法需要引用System.Linq
. 阅读更多关于 Any()