Recently, I was preparing to work with my friends to draft a basic series of video tutorials. So I found some basic things. Sometimes the basic things are also very interesting, but they are actually deeper. For example, the difference and relationship between Disponse () and Close () have never been concerned about why they were designed like this.
Sometimes someone may ask the following question: when we develop C # code, we often encounter a problem. Some classes provide Close () and some classes provide Dispose (), in addition, some classes also provide Dispose (bool). What is the difference between Dispose and Close?
1. Is Close () more intuitive ?!
Maybe Close () is designed for developers who are not familiar with Dispose (), because basically all developers know what Close () is, after all, it has an intuitive name. But I think this is not the main reason, mainly because of the design pattern.
Ii. design modes of Close () and Dispose ()
In. in the Net Framework, Close () is designed to be public, and hidden Dispose () is called in Close (); then Dispose () calls another virtual Dispose (bool) function. Therefore, if you inherit from this class, you must implement the Dispose (bool) method. By calling Close (), the caller indirectly calls the overloaded Dispose (bool) method to release the resource.
3. Close () should not be defined as virtual
Because Close () is only used to call the hidden Dispose () and then call Dispose (bool), the user should not change the Close behavior. For this purpose, System. IO. Stream has design problems. The reason may be to meet the needs of backward compatibility. Therefore, we can find in the MSDN document that, although Close () is virtual, it should not be override.
IV. Implementation Mode of the IDisposable Interface
Classes with the Disponse () method implement the IDisposable interface .. In Net, many classes only provide Close () instead of Disponse (), but it does implement the IDisponse interface. Why?
The reason is that the interface implementation mode is explicit implementation or implicit implementation. The difference between the two is that for implicit implementation, you only need to call "new ClassA (). dispose () ", but for explicit implementation, Dispose () is not a member function of this ClassA. The only method of calling is to forcibly convert the type to IDisposable, that is, "new ClassA (). dispose () "is not compiled, but (IDisposable) new ClassA ()). dispose () can be compiled. Therefore, it meets the design requirements: provide Close (), hide Dispose (), and implement the IDisposable interface.