Recommendation 51: Types with disposable fields or types that own native resources should be disposable
In recommendation 50, we divide the types in C # into ordinary types and non-trivial types that inherit the IDisposable interface. Non-trivial types, in addition to the types that contain those managed resources, themselves contain a field of a non-trivial type.
In the standard dispose mode, we give an example of a non-trivial type: an Anotherresource type. Since Anotherresource is a non-trivial type, if there is a type that combines anotherresource, then he should inherit the IDisposable interface:
classanothersampleclass:idisposable {PrivateAnotherresource Managedresource =NewAnotherresource (); Private BOOLdisposed =false; Public voidDispose () {Dispose (true); Gc. SuppressFinalize ( This); } ~Anothersampleclass () {Dispose (false); } protected Virtual voidDispose (BOOLdisposing) { if(disposed) {return; } if(disposing) {//clean up Managed resources if(Managedresource! =NULL) {managedresource.dispose (); Managedresource=NULL; }} disposed=true; } Public voidSamplepublicmethod () {if(disposed) {Throw NewObjectDisposedException ("Anothersampleclass","Anothersampleclass is disposed"); } //omitted } }
Type Anothersampleclass Although it does not contain any explicit unmanaged resources, because it contains a non-trivial type, we still have to implement a standard dispose pattern for it.
In addition, a type has a native resource (that is, an unmanaged resource) and it should inherit the IDisposable interface.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 51: Types with disposable fields or types that own native resources should be disposable