问题
I was reading about StreamWriter
today, and came across this property, BaseStream
.
I was looking for a definition and found this
"Gets the underlying stream that interfaces with a backing store."
from here MSDN - StreamWriter.BaseStream
I understand what a BaseStream is for StreamReader, because it's definition is very simply:
Returns the underlying stream.
But what does the definition of the StreamWriter.BaseStream mean?? Or more clearly, what does this part of the definition mean "interfaces with a backing store"? That sounds like gibberish to me.
回答1:
You're right; it does seem unnecessarily wordy, especially in comparison with the analogous StreamReader.BaseStream
. In reality, it just returns a reference to the underlying stream, exactly like StreamReader.
I think the presumption of the description is that writing to the underlying stream will involve saving the written data to some sort of persistent store, such as a file. Of course, this isn't necessary at all in reality (in the worst case, it could simply do nothing).
If you really wanted to extrapolate, you could interpret that as meaning that the underlying stream's CanWrite
property is true
(at least at the point it was attached to the StreamWriter).
To be convinced that it really is just returning the underlying stream, here's the decompiled code from Reflector:
public virtual Stream BaseStream
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get
{
return this.stream;
}
}
where the stream
field is assigned in the Init
method:
private void Init(Stream stream, Encoding encoding, int bufferSize)
{
this.stream = stream;
...
which in turn is called by the constructor with the argument being the attached stream:
[SecuritySafeCritical]
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: base(null)
{
...
this.Init(stream, encoding, bufferSize);
}
回答2:
So the generic definition of Stream
is this:
Provides a generic view of a sequence of bytes.
and StreamWriter
:
Implements a TextWriter for writing characters to a stream in a particular encoding.
So the BaseStream
property is where the characters will be written to. This may be a FileStream
or a MemoryStream
or anything else that implements Stream
. I feel like a better description would be:
Gets the underlying stream.
回答3:
I think it is for when you "daisychain" streams.
Eg your code writes to stream A, which writes to stream B, which writes to stream C, which writes to disk.
Stream A's basestream is B in that instance.
来源:https://stackoverflow.com/questions/4653543/net-streamwriter-basestream-what-does-this-definition-mean-gets-the-underlyi