处理新表格的正确方法 [英] Proper way to dispose a new Form

查看:28
本文介绍了处理新表格的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的应用中,我倾向于动态创建新的表单实例,然后使用 Form.Show() 来显示它们(非模态).

So in my apps, I tend to create new instances of forms on the fly, then use Form.Show() to display them (non modal).

private void test_click(object sender, EventArgs e)
{
    var form = new myForm();
    form.Show();
}

但是,Code Cracker 告诉我应该处理这些表单.所以,我用using"语句包裹了它们,但它们在打开后立即关闭.

However, Code Cracker tells me that these forms should be disposed. So, I wrapped them with the "using" statement, but then they close immediately after opening.

using (var form = new myForm())
{
    form.Show();
}

我不想使用Form.ShowDialog(),因为在某些情况下我会打开只显示报告的新窗口;我不需要它们是模态的.

I don't want to use Form.ShowDialog(), because in a few instances I'm opening new windows that only show reports; I don't need them to be modal.

推荐答案

嗯,代码破解器"似乎是该工具的一个非常合适的术语,它的建议无疑使您编写了破坏程序的代码.黄金法则是永远相信来自静态代码分析工具的 IDisposable 建议,他们都对代码执行有足够的洞察力.他们永远无法弄清楚哪个 Dispose() 调用完成了工作.

Hmm, "code cracker" appears to be a very appropriate term for that tool, its advice certainly made you write code that breaks your program. Golden Rule is to never trust IDisposable advice from a static code analysis tool, none of them ever have sufficient insight in code execution. They can never figure out which Dispose() call gets the job done.

它看不到的是Form类已经知道如何处置自己了.这样做很容易,当窗口关闭时对象变得不可用.当没有更多窗口时,就没有理由继续使用 Form 对象.这种奢侈品在 .NET 中并不常见,但肯定受到 45 年前为 Xerox 工作的非常聪明的程序员的启发.

What it cannot see is that the Form class already knows how to dispose itself. It is very easy for it to do so, the object becomes unusable when the window closes. When there is no more window then there's no reason to keep using the Form object. A luxury that isn't otherwise very common in .NET but certainly inspired by very smart programmers that worked for Xerox 45 years ago.

您只需要记住一个特殊规则,当您使用 ShowDialog() 显示窗口时,它不会自行处理.这是故意的,它使检索对话结果的风险太大.对 ShowDialog() 调用使用 using 语句非常容易,该调用在窗口关闭之前不会返回.

There is only one special rule you have to keep in mind, it does not dispose itself when you use ShowDialog() to display the window. That was intentional, it makes retrieving the dialog results too risky. Using the using statement for a ShowDialog() call is very easy to do, the call does not return until the window is closed.

这篇关于处理新表格的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆