简体   繁体   English

WebResponse在实现IDisposable时如何不公开显示“Dispose”?

[英]How does WebResponse not have “Dispose” publically visible when it implements IDisposable?

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. 通过最近涉及WebResponse的一些代码调试后,我发现我遇到的问题是我在发出另一个之前没有正确处理WebResponse。 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). 因为WebResponse需要被转换为IDisposable以便实际调用dispose(或者你可以使用“using”来实现相同的目标),所以我误入歧途。

So my questions are: 所以我的问题是:

1) What is Microsoft using to accomplish this? 1)Microsoft用什么来实现这一目标?

IDisposable is an interface and therefore public, yet somehow WebResponse alters the access modifier to be protected according to the MSDN doumentation. IDisposable是一个接口,因此是公共的,但WebResponse以某种方式改变了根据MSDN doumentation保护的访问修饰符。 I thought this was impossible. 我认为这是不可能的。

2) What is the benefit of hiding the dispose in this manner? 2)以这种方式隐藏处置有什么好处?

Why not just let webResponse.Dispose() be valid? 为什么不让webResponse.Dispose()有效?

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. using API知道使用IDisposable实现。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM