Do I need to call Dispose() on managed objects?

后端 未结 11 1847
忘了有多久
忘了有多久 2020-12-08 14:51

I can\'t believe I\'m still confused about this but, any way, lets finally nail it:

I have a class that overrides OnPaint to do some drawing. To speed things up, I c

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 15:11

    You really need to look up the documentation for the brushes, pens etc.

    If they aren't using unmanaged resources, you may not have to call Dispose. But the using/Dispose pattern is sometimes "misused". As an example, consider the ASP.NET MVC framework. Here you can write something like:

    using(Html.BeginForm(...)){
      ///HTML input fields etc.
    }
    

    When Html.BeginForm(...) is called, a FORM tag will be output. When the using-statement ends, Dispose will be called on the object returned from Html.BeginForm(...). Calling Dispose causes the end FORM tag to be rendered. In this way the compiler will actually enforce the pairing of FORM tags, so you won't forget the closing tag.

提交回复
热议问题