MSDN C# DeflateStream 示例代码问题
知道为什么在下面的示例中我们需要添加 100 (buffer.Length + 100) 吗? buffer.Length 应与解压后的缓冲区长度相同,因此无需再添加 100。 :-)
http://msdn.microsoft.com/en-us/library /bc2dbwea.aspx
提前致谢, 乔治
Any ideas why in the below sample, we need to add 100 (buffer.Length + 100)? buffer.Length should be the same as decompressed buffer length, so no need to add 100 more. :-)
http://msdn.microsoft.com/en-us/library/bc2dbwea.aspx
thanks in advance,
George
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道他们为什么这样做,但这通常不是一个很好的例子 - 例如,他们在
Close
上使用显式调用(不在finally块中) >FileStream 而不是使用using
语句,并且还假设对Read
的单个调用将读取整个文件。 哎呀,即使将整个文件读入缓冲区也是一个坏主意 - 最好一次直接将一个块复制到DeflateStream
中。这些事情向我表明,不值得担心该示例中这个特定的奇怪代码(额外的 100 字节)。 当然不要将其视为“最佳实践”。
MSDN 的例子通常比这个更好——尽管还有很多其他奇怪的例子。
编辑:重新阅读代码和 CodeMelt 的答案后,它确实需要额外的 100 个字节 - 但这只是因为 ReadAllBytesFromStream 实现得如此糟糕。 这是一个更好的实现,它总是要求流填充缓冲区的其余部分:(
请注意,不需要
offset
和totalCount
因为它们始终具有相同的值价值。)I don't know why they're doing that, but it's not a great example in general - for instance, they're using explicit calls to
Close
(not in a finally block) on theFileStream
instead of using ausing
statement, and also assuming that a single call toRead
will read the whole of a file. Heck, even reading the whole file into a buffer is a bad idea - it would be better to copy a chunk at a time straight into theDeflateStream
.These things suggest to me that it's not worth worrying about this specific odd bit of code (the extra 100 bytes) within that example. Certainly don't regard it as "best practice".
MSDN examples are usually better than this - although there are plenty of other odd ones.
EDIT: Having reread the code and CodeMelt's answer, it does indeed need the extra 100 bytes - but only because ReadAllBytesFromStream is implemented so badly. Here's a better implementation, which always asks the stream to fill the rest of the buffer:
(Note that there was no need for both
offset
andtotalCount
as they always had the same value.)它可以防止 Stream.Read(buffer, offset, 100) 在以下方法中超出其长度,因为流会一直读取,直到什么也读不到。
It prevents stream.Read(buffer, offset, 100) from going over its length within the following method because the stream keeps reading until it reads nothing.