假设我使用此方法将字节缓冲区复制到内存流中
memoryStream.Read(data, 0, data.Length);
Run Code Online (Sandbox Code Playgroud)
有没有办法让我清空流并重用它来读取其他数据?
我想避免创建许多MemoryStream对象,而是希望使用一个实例,在用法之间重置它
Chr*_*lor 32
您可以通过将Position设置为0并将Length设置为0来重新使用MemoryStream.
MemoryStream ms = new MemoryStream();
// Do some stuff with the stream
// Reset the stream so you can re-use it
ms.Position = 0; // Not actually needed, SetLength(0) will reset the Position anyway
ms.SetLength(0);
// Do some more stuff with the stream
Run Code Online (Sandbox Code Playgroud)
通过将长度设置为0,您不会清除现有缓冲区,它只会重置内部计数器.因此,现有的缓冲区分配保持不变,但是重置所有缓冲区的所有簿记都会被重置,以便您可以重新使用它.
更新:我刚看了一下SetLength的代码实现,如果你将长度设置为0,Position会自动重置为0,所以你甚至不需要显式设置Position属性就足以重置长度.