Why is there no RAII in .NET?

后端 未结 7 932
生来不讨喜
生来不讨喜 2020-12-04 14:59

Being primarily a C++ developer the absence of RAII (Resource Acquisition Is Initialization) in Java and .NET has always bothered me. The fact that the onus of cleaning up i

相关标签:
7条回答
  • 2020-12-04 15:54

    IMHO, the big things that VB.net and C# need are:

    1. a "using" declaration for fields, which would cause the compiler to generate code to dispose of all fields thus tagged. The default behavior should be for the compiler to make a class implement IDisposable if it does not, or insert disposal logic before the start of the main disposal routine for any of a number of common IDisposal implementation patterns, or else use an attribute to specify that the disposal stuff should go in a routine with a particular name.
    2. a means of deterministically disposing of objects whose constructors and/or field initializers throw an exception, either by a default behavior (calling the default disposal method) or a custom behavior (calling a method with a particular name).
    3. For vb.net, an auto-generated method to null out all WithEvent fields.

    All of those can be kludged pretty well in vb.net, and somewhat less well in C#, but first-class support for them would improve both languages.

    0 讨论(0)
提交回复
热议问题