C#:使用语句和 this 关键字

C# : Using statement and this keyword

在想使用using语句的时候遇到了一个不明白的场景:

private void RoomMealHistory_Click(object sender, EventArgs e)
    {
        MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true);
        fMealRoomPlanning .MdiParent = this;
        fMealRoomPlanning.Show(); 
    }

这段代码工作正常,我的 window 是一个 MdiChild。

但是,以下代码不起作用:

private void RoomMealHistory_Click(object sender, EventArgs e)
    {
        using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
        {
            MdiParent = this;
            fMealRoomPlanning.Show();
        }
    }

ArgumentException: '一个窗体不能同时是 MDI 子级和 MDI 父级。

我也试过用 this.ParentForm 替换这个已经不行了。

这个范围有问题吗?

在您的第一个片段中,您设置了 fMealRoomPlanning 的 MdiParent-属性。

在您的第二个代码段中,您设置了自己的 class 实例 (this.MdiParent) 的 MdiParent。

您应该将其设置在您正在使用的对象上:

private void RoomMealHistory_Click(object sender, EventArgs e)
    {
        using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
        {
            fMealRoomPlanning.MdiParent = this;
            fMealRoomPlanning.Show();
        }
    }

这就是为什么许多样式检查建议使用 this-Qualifier,尽管它是多余的。如果您设置本地、全局或 class 变量,这会更清楚。

尝试将 MdiParent = this 更改为 fMealRoomPlanning.MdiParent = this

尝试更改第二个代码,在为 MealRoomPlanning class 创建 object 之后 将 MdiParent = this; 更改为 fMealRoomPlanning.MdiParent = this;

private void RoomMealHistory_Click(object sender, EventArgs e)
{
    using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
    {
        fMealRoomPlanning.MdiParent = this;
        fMealRoomPlanning.Show();
    }
}

终于明白非模态Form不需要Using了

When a non modal form is closed, the Dispose will automatically be called by WinForms.

与使用 ShowDialog 打开的表单不同,后者不会自动调用 Dispose。