Proper way to dispose a new Form

前端 未结 4 2055
囚心锁ツ
囚心锁ツ 2020-11-27 22:15

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



        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 23:06

    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.

提交回复
热议问题