什么是处置不立即关闭一种新形式的正确方法? [英] What's the proper way to dispose of a new form without it closing immediately?

查看:154
本文介绍了什么是处置不立即关闭一种新形式的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我的应用程序,我更倾向于动态创建的形式新实例,然后使用Form.Show()来显示它们(非模态)。



<预类=郎-CS prettyprint-覆盖> 私人无效test_click(对象发件人,EventArgs五)
{
变种形式=新建MyForm();
form.Show();
}



不过,代码饼干告诉我,这些形式应该进行处理。所以,我包裹它们与使用的声明,但他们开场后立即关闭。



<预类=郎-CS prettyprint-覆盖> 使用(VAR形式=新建MyForm())
{
form.Show();
}



我不想使用Form.ShowDialog(),因为在一个少数情况下,我打开新窗口只显示报告;我并不需要他们的模态。


解决方案

嗯,码骇客似乎是该工具非常合适的术语,它的建议肯定让你编写的代码伤了你的计划。金科玉律是的从不的从静态代码分析工具的信任IDisposable的意见,他们都曾经有代码的执行的足够的洞察力。他们永远无法弄清楚它的Dispose()调用能够完成任务。



什么不能看到的是,Form类已经知道如何处理自己。这是很容易为它这样做,当窗口关闭对象变得不可用。如果没有更多的窗口,那么就没有理由继续使用Form对象。一种奢侈品,是不是另有.NET很常见的,但肯定由45年前施乐工作非常聪明的程序员的启发。



有只有一个你有特殊规则要记住,它的的当您使用ShowDialog的()显示窗口处理本身。这是故意的,它使得检索结果对话框风险太大。使用的使用的一个ShowDialog的()调用语句是很容易做到的,呼叫不返回,直到窗口被关闭。


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();
}

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();
}

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.

解决方案

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.

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.

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