How does WebResponse not have "Dispose" publically visible when it implements IDisposable?

StackOverflow https://stackoverflow.com/questions/19503271

سؤال

After debugging through some code recently involving WebResponse, I found that the issue I had was that I was not properly disposing of the WebResponse before issuing another one. I was lead astray since WebResponse needs to be cast as an IDisposable in order to actually call dispose (or you can use "using" to achieve the same goal).

So my questions are:

1) What is Microsoft using to accomplish this?

IDisposable is an interface and therefore public, yet somehow WebResponse alters the access modifier to be protected according to the MSDN doumentation. I thought this was impossible.

2) What is the benefit of hiding the dispose in this manner?

Why not just let webResponse.Dispose() be valid?

هل كانت مفيدة؟

المحلول

Explicit interface implementation:

public class Foo : IDisposable {
    void IDisposable.Dispose() { /* code here */ }
}

This can be done with any interface method. The using API knows to use the IDisposable implementation.

Note that this feature should not be over-used; the following would be confusing, for example:

public class Foo : IDisposable {
    void IDisposable.Dispose() { /* do something */ }
    public void Dispose() { /* do something completely different */ }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top