简体   繁体   English

IDisposable.Dispose()作为方法名称是什么意思?

[英]What does IDisposable.Dispose() as a method name mean?

I was just tidying up some code when I found this region in the class: 当我在课堂上找到这个区域时,我只是整理了一些代码:

    #region IDisposable Members

        void IDisposable.Dispose()
        {
        } 

     #endregion

Now understand that this is implementing the Dispose method for the IDisposable interface and I know that the class declaration says that this class will implement the IDisposable interface. 现在明白这是为IDisposable接口实现Dispose方法,我知道类声明说这个类将实现IDisposable接口。

What I don't get is why it reads: 我没有得到的是为什么它写道:

void IDisposable.Dispose()

And not: 并不是:

public void Dispose()

I guess that the IDisposable.Dispose indicated explicitly that this is the Dispose that implements the IDisposable interface? 我猜IDisposable.Dispose明确指出这是实现IDisposable接口的Dispose? Is this correct and what's the advantage of doing this? 这是正确的,这样做有什么好处?

It is an explicit interface implementation . 它是一个显式的接口实现

It means that only a variable of type IDisposable can call Dispose on this class. 这意味着只有IDisposable类型的变量才能在此类上调用Dispose

Doing so "hides" the Dispose method when used with a variable of the class type - it will not be able to call it directly without first casting to IDisposable . 当与类类型的变量一起使用时,这样做“隐藏” Dispose方法 - 如果没有首先转换为IDisposable ,它将无法直接调用它。 It is possible that the implementer did this on purpose. 实施者有可能故意这样做。

Additionally, if the class were to implement its own Dispose (or inherit/implement from a class/interface that also defines a Dispose method), this will allow multiple implementations to exist. 另外,如果类要实现自己的Dispose (或者从也定义Dispose方法的类/接口继承/实现),这将允许存在多个实现。

That's an explicit interface implementation . 这是一个明确的接口实现 Useful if a class implements several interfaces that have the same methods. 如果一个类实现了几个具有相同方法的接口,则非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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