1

我有一个 MemoryStream /BinaryWriter ,我使用它如下:

memStram = new MemoryStream();
memStramWriter = new BinaryWriter(memStram);

memStramWriter(byteArrayData);

现在阅读我执行以下操作:

byte[] data = new byte[this.BulkSize];
int readed = this.memStram.Read(data, 0, Math.Min(this.BulkSize,(int)memStram.Length));

我的2个问题是:

  1. 我读完后,位置移动到 currentPosition+readed , memSram.Length 会改变吗?
  2. 我想初始化流(就像我刚刚创建它一样),我是否可以再次使用 Dispose 和 new 来执行以下操作,如果没有,是否有比 dispose&new 更快的方法:
memStram.Position = 0;
memStram.SetLength(0);

谢谢。约瑟夫

4

3 回答 3

3
  1. 不; 为什么读取时长度(即数据大小)要改变?
  2. 是的; SetLength(0) 更快:在这种情况下,内存分配和重新分配没有开销。
于 2013-08-07T08:24:09.640 回答
2

1: After I read, the position move to currentPosition+readed , Does the memStram.Length will changed?

Reading doesn't usually change the .Length - just the .Position; but strictly speaking, it is a bad idea even to look at the .Length and .Position when reading (and often: when writing), as that is not supported on all streams. Usually, you read until (one of, depending on the scenario):

  • until you have read an expected number of bytes, for example via some length-header that told you how much to expect
  • until you see a sentinel value (common in text protocols; not so common in binary protocols)
  • until the end of the stream (where Read returns a non-positive value)

I would also probably say: don't use BinaryWriter. There doesn't seem to be anything useful that it is adding over just using Stream.

2: I want to init the stream (like I just create it), can I do the following instead using Dispose and new again, if not is there any faster way than dispose&new:

Yes, SetLength(0) is fine for MemoryStream. It isn't necessarily fine in all cases (for example, it won't make much sense on a NetworkStream).

于 2013-08-07T08:20:23.623 回答
2

不,长度不应该改变,您可以使用手表变量轻松检查

我会使用该using语句,因此语法会更加优雅和清晰,并且您以后不会忘记处置它...

于 2013-08-07T08:23:49.813 回答