问题描述
在.NET 4中引入一个有用的方便是 Stream.CopyTo(Stream[,的Int32])的强>读取从当前流的内容并将其写入到另一个流。
A useful convenience introduced in .NET 4 is Stream.CopyTo(Stream[, Int32]) which reads the content from the current stream and writes it to another stream.
这避免了需要稍微繁琐$c$c像这样的:
This obviates the need for slightly tedious code such as this:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write (buffer, 0, read);
}
}
由于我没有.NET 4中安装了这台机器上,我在想,如果谁的人有安装可以打开反射向我们展示了如何在框架类库团队实施这种方法的.NET 4 .NET 4
Since I don't have .NET 4 installed on this machine, I was wondering if someone who has .NET 4 installed could open up Reflector and show us how the Framework Class Library team implemented this method for .NET 4.
比较和对比实施上述code段。特别是,我想知道是什么选择默认的缓冲区大小。
Compare and contrast their implementation with code snippet above. In particular, I'm interested to know what default buffer size was chosen.
推荐答案
在.NET 4.5.1,它使用81920字节的固定的缓冲区大小。 (早期版本的.NET使用4096字节的固定的缓冲区大小,并且它无疑将继续随时间而改变。)还有一个重载,你可以通过自己的缓冲区大小。
In .NET 4.5.1, it uses a fixed buffer size of 81920 bytes. (Earlier versions of .NET used a fixed buffer size of 4096 bytes, and it will no doubt continue to change over time.) There is also an overload where you can pass your own buffer size.
的实施是非常相似的你,有些模洗牌周围和一些错误检查。反射使得它的心脏如下:
The implementation is very similar to yours, modulo some shuffling around and some error checking. Reflector renders the heart of it as follows:
private void InternalCopyTo(Stream destination, int bufferSize)
{
int num;
byte[] buffer = new byte[bufferSize];
while ((num = this.Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, num);
}
}
(现在你可以看到实际的源处的.)
该错误检查基本上是围绕input.CanRead和output.CanWrite是否都是真实的,或任一配置。所以在回答Benny的问题,这应该是非常幸福的复制,从一个的NetworkStream(或可写的NetworkStream)。
The error checking is basically around whether input.CanRead and output.CanWrite are both true, or either is disposed. So in answer to Benny's question this should be perfectly happy copying from a NetworkStream (or to a writable NetworkStream).
这篇关于如何在Stream.CopyTo(流)方法来实现在.NET 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!