问题
Having this code:
using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create)))
{
//save something here
}
Do we need to close the BinaryWriter? If not, why?
回答1:
So long as it's all wrapped up in a using block then you don't need to explicitly call Close.
The using block will ensure that the object is disposed, and the Close and Dispose methods are interchangeable on BinaryWriter. (The Close method just calls Dispose behind the scenes.)
回答2:
Putting it in a using statement as per your code example will call Dispose, which closes the underlying stream, so no. You can see this through Reflector:
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.OutStream.Close();
}
}
回答3:
With the code you have there it will close the file once it exits the using block, so you do not need to call close explcitly.
The only reason not to use the using statement would be if you want the file to still be open after you are done with your BinaryWriter, in which case you should hold on to a reference of it instead of passing it into the constructor like that.
回答4:
The using block will automaticlly close the binary writer and put it in a state to be GC'ed. Using blocks are syntactic sugar for doing the exception handling and closing of the stream yourself.
回答5:
By wrapping the writer up in a using block, the close will automatically happen when the writer is disposed. So in this case, you don't need to explicitly close the writer.
来源:https://stackoverflow.com/questions/1079434/do-we-need-to-close-a-c-sharp-binarywriter-or-binaryreader-in-a-using-block