为什么在BinaryReader上调用Dispose()会导致编译错误? [英] Why calling Dispose() on BinaryReader results in compile error?

查看:98
本文介绍了为什么在BinaryReader上调用Dispose()会导致编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following class which uses BinaryReader internally and implements 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才能调用对其进行处理,但是我不明白为什么不能不转换为IDisposable而直接调用Dispose()方法吗?

I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don't understand why I can't just call the Dispose() method directly without casting to IDisposable?

推荐答案

该方法不起作用,因为已经明确实现了 BinaryReader 上的 Dispose 方法。

It won't work because the Dispose method on BinaryReader has been explicitly implemented.

不是被隐式实现,例如:

Instead of being implicitly implemented, as in:

public void Dispose()
{
}

...它已明确实现,如: / p>

...it has been explicitly implemented, as in:

void IDisposable.Dispose()
{
}

...这意味着只能通过 IDisposable 界面进行访问。因此,必须首先将实例转换为 IDisposable

...which means it can only be accessed via the IDisposable interface. Therefore, you have to cast the instance to IDisposable first.

这篇关于为什么在BinaryReader上调用Dispose()会导致编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆