[英]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 替换它。ParentForm 不再起作用。
这个的scope有问题吗?
在您的第一个片段中,您设置了 fMealRoomPlanning 的 MdiParent-Property。
在您的第二个片段中,您设置了您自己的 class 实例 ( this.MdiParent
) 的 MdiParent。
您应该在您使用的 object 上设置它:
private void RoomMealHistory_Click(object sender, EventArgs e)
{
using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
{
fMealRoomPlanning.MdiParent = this;
fMealRoomPlanning.Show();
}
}
这就是为什么许多样式检查建议使用this
-Qualifier 尽管它是多余的。 如果您设置了本地、全局或 class 变量,这将更加清楚。
最后我刚刚明白,非模态表单不需要使用。
当非模态窗体关闭时,WinForms 会自动调用 Dispose。
与使用 ShowDialog 打开的 Forms 不同,不会自动调用 Dispose。
尝试将MdiParent = this
更改为fMealRoomPlanning.MdiParent = this
尝试更改第二个代码,在为MealRoomPlanning class 创建object之后更改MdiParent = this; 到fMealRoomPlanning.MdiParent = 这个;
private void RoomMealHistory_Click(object sender, EventArgs e)
{
using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
{
fMealRoomPlanning.MdiParent = this;
fMealRoomPlanning.Show();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.