How is IDisposable implemented on FileStream in .Net 1.1

心已入冬 提交于 2019-12-10 14:43:42

问题


This might seem like a noddy question, but I was looking at this because I heard someone claiming that you must call Close() on a FileStream, even if it is in a using block (and they have code where Close() is being called right at the end of the block).

I know that Close() is meant to call Dispose(), but I thought I'd look deeper since this is .Net 1.1 code, and the bulk of my experience has been with 2.0 on.

One thing that struck me was that the MSDN documentation for FileStream has Dispose() and Dispose(bool) for .Net 2.0 on, but only Dispose(bool) for .Net 1.1.

I thought that might be an oversight, so I used Reflector to look into an assembly - and there too, I see Dispose(bool), but no Dispose().

Is this correct? If so, what's the story here? FileStream works in a using block - which I thought meant it must implement IDisposable which, to my knowledge only declares Dispose().

Is there some compiler magic going on, or am I missing a hidden implementation of Dispose() somewhere (which, presumably, calls Dispose(true) or Dispose(false) ? )

Finally (no pun intended), can you confirm that scoping a FileStream in using block will close stream at scope exit in .Net 1.1?

[edit]

Just to clarify, this is C# code. I understand that VB.Net didn't get the using statement until .Net 2.0, but my understanding is that C# had it in 1.1 (and my 1.1 code here has it in and it compiles)


回答1:


It's implemented a little funny, but it's there: The base class for FileStream: System.IO.Stream implements IDisposable (FileStream just inherits it).

The base stream class implements Dispose() explicitly, so you will only see Dispose() if you cast the stream as IDisposeable (which is what using{} does).

Stream.Dispose() calls Stream.Close().

(got all this via Reflector)



来源:https://stackoverflow.com/questions/939124/how-is-idisposable-implemented-on-filestream-in-net-1-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!