Handling IDisposable in failed initializer or constructor

前端 未结 5 529
名媛妹妹
名媛妹妹 2020-12-11 06:34

Is there any nice pattern in .Net for ensuring that IDisposable fields owned by an object will get disposed if an exception is thrown during construction, possi

5条回答
  •  半阙折子戏
    2020-12-11 06:45

    In C# you would use 'using':

            using(DisposableObject obj = new DisposableObject()) {
            }
    

    VB also has a Using...End Using construct. When using these the Dispose method is guaranteed to be called, even in the event of an exception. You can release any resources created by the initializers (or the constructor) in the Dispose method.

提交回复
热议问题