使用 Linq 关闭所有 MDI 子窗口

gre*_*ian 3 c# linq mdiparent mdichild winforms

我正在尝试使用以下循环

foreach (Form frm in this.MdiChildren)
{
    frm.Close();
}
Run Code Online (Sandbox Code Playgroud)

并将其转录为 Linq 表达式,如下所示:

this.MdiParent.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Close());
Run Code Online (Sandbox Code Playgroud)

但这一行向我显示了NullReferenceException“未将对象引用设置为对象的实例”

我究竟做错了什么?我是 Linq 的新手。

Han*_*año 5

尝试这个:

this.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Close());
Run Code Online (Sandbox Code Playgroud)

除非您从其中一个孩子那里尝试该代码,在这种情况下,您可以尝试您的代码

this.MdiParent.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Close());
Run Code Online (Sandbox Code Playgroud)

它也应该工作。