BinaryReader.Dispose(bool disposing)创建一个对stream的本地引用。 为什么?

我在FCL代码中发现了一个不寻常的样本。

这是System.IO.BinaryReader中的方法:

protected virtual void Dispose(bool disposing) { if (disposing) { Stream copyOfStream = m_stream; m_stream = null; if (copyOfStream != null && !m_leaveOpen) copyOfStream.Close(); } m_stream = null; m_buffer = null; m_decoder = null; m_charBytes = null; m_singleChar = null; m_charBuffer = null; } 

“copyOfStream”对执行逻辑有什么影响?

这样做即使Stream.Close()抛出exception,m_stream也将设置为null。

回应评论

可以在Stream.Close()上引发什么样的exception

当您关闭流时,将刷新任何缓冲的输出,这可能会引发exception,例如由于网络故障。

我不确定这是理由。 通常我们在使用块时调用Dispose,这意味着变量永远不会被使用

在上面,如果抛出Stream.Close(),那么m_stream将已经为null。 使用以下替代方法,如果Stream.Close()抛出,则m_stream将不会设置为null:

 m_stream.Close(); // <== throws m_stream = null; // <== not executed if Close() throws 

但在这种情况下,如果我们谈论exception安全,有人可以重试对Dispose方法的调用,并将面临NullReferenceException

它不会抛出NullReferenceException,因为它测试null:

 if (copyOfStream != null && !m_leaveOpen) copyOfStream.Close();