为什么在BinaryReader上调用Dispose()会导致编译错误?

Mic*_*ski 2 .net c#

我有以下类在内部使用BinaryReader并实现IDisposable.

class DisposableClass : IDisposable
    {
        private BinaryReader reader;
        public DisposableClass(Stream stream)
        {
            reader = new BinaryReader(stream);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                ((IDisposable)reader).Dispose();
//                reader.Dispose();// this won't compile
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
        }
    }

我已经发现我需要将BinaryReader转换为IDisposable以便能够在其上调用Dispose,但我不明白为什么我不能直接调用Dispose()方法而不转换为IDisposable?

Jef*_*tes 7

它不起作用,因为已经明确实现了Disposeon on方法BinaryReader.

而不是隐式实现,如:

public void Dispose()
{
}
Run Code Online (Sandbox Code Playgroud)

......已经明确实施,如:

void IDisposable.Dispose()
{
}
Run Code Online (Sandbox Code Playgroud)

...这意味着它只能通过IDisposable界面访问.因此,您必须IDisposable先将实例强制转换.