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

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

问题描述

因此,在我的应用中,我倾向于动态创建表单的新实例,然后使用 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.

推荐答案

嗯,代码破解程序似乎是该工具的一个非常合适的术语,其建议无疑使您编写了以下代码:破坏您的程序。黄金法则是永远不要信任静态代码分析工具中的IDisposposable建议,他们都不会对代码执行有足够的了解。他们永远无法弄清楚哪个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()显示窗口时,它不会自动处理。这是故意的,这使得检索对话框结果的风险太大。将 using 语句用于ShowDialog()调用非常容易,直到关闭窗口后该调用才会返回。

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天全站免登陆