MemoryStream:为什么在readByte之后转换为byte
在MS 的这个示例中,您会注意到在我们读取一个字节后从内存流中,它进入一个 int,然后必须将其转换为 byte。让我感到奇怪的是,像 .ReadByte()
这样的函数一开始就不返回字节。 MS这样做有什么原因吗?
// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
byteArray[count++] =
Convert.ToByte(memStream.ReadByte());
}
我想到了一个想法。也许这取决于使用情况。也许ReadByte()
经常用于检索短长度,随后在通过长度变化的检索中消耗它
int length=ms.ReadByte();
ms.Read(buf,0,lenth);
,即您可以使用不进行强制转换的长度。这是一个足够好的理由吗?
In this example from MS, you'll notice that after we read a byte from memory stream, it goes into an int which must then be converted to byte. It stikes me as strange that a function like .ReadByte()
doesn't return a byte in the first place. Is there a reason why MS did it this way?
// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
byteArray[count++] =
Convert.ToByte(memStream.ReadByte());
}
a thought occured to me. Perhaps this comes down to usage. Perhaps ReadByte()
is often used to retrieve short lengths, which subsequents get consumed in the retrieve via length variety
int length=ms.ReadByte();
ms.Read(buf,0,lenth);
i.e. you can use the length without a cast. Is this a good enough reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这并不是Memory Stream特有的,而是因为基类“Stream”的设计,其原因是
返回值:
-1不能用无符号字节表示
This is not specific to Memory stream, rather it is because of the design of base class "Stream" and the reason for that is
Return value:
-1 cannot be represented using unsigned byte
当您使用
ReadByte
时,如果读取成功,则流中的当前位置将前进一个字节。但它的设计是如果到达流末尾则返回 -1。现在,这将不是
Byte
的有效值(其无符号)ms.Read(buf,0,lenth);
这里 lenth 是要从流,你从 ReadByte 得到的是第一个字节,它不能以这种方式使用,比如When you use
ReadByte
If the read is successful then the current position within the stream is advanced by one byte. but its designed to return -1 if the end of the stream has been reached.Now this would not be a valid value for
Byte
(its unsigned)ms.Read(buf,0,lenth);
here lenth is the number of bytes to read from the stream and what you get fromReadByte
is first byte its not be used in the this fashion, something like我确实相信他们正在以一种非常好的方式从
int
转换为byte
,因为ReadByte()
返回一个 int 和他们的byteArray
的类型为int[]
。I do believe they are converting with that from
int
tobyte
in a reallllllly nice way, sinceReadByte()
returns an int and theirbyteArray
is of typeint[]
.