What's the purpose of implementing the IDisposable interface?

后端 未结 5 984
无人及你
无人及你 2021-01-13 13:05

What\'s the purpose of implementing the IDisposable interface? I\'ve seen some classes implementing it and I don\'t understand why.

5条回答
  •  星月不相逢
    2021-01-13 13:58

    As well as freeing unmanaged resources, objects can usefully perform some operation the moment they go out of scope. A useful example might be an timer object: such objects could print out the time elapsed since their construction in the Dispose() method. These objects could then be used to log the approximate time taken for some set of operations:

    using(Timer tmr=new Timer("blah"))
    {
        // do whatever
    }
    

    This can be done manually, of course, but my feeling is that one should take advantage wherever possible of the compiler's ability to generate the right code automatically.

提交回复
热议问题