MemoryStream的:为什么readByte后转换为字节转换为、字节、MemoryStream、readByte

2023-09-04 00:52:45 作者:愛上妳怎麽辦

在这个例子从MS ,你会发现,当我们从内存中读取数据流的一个字节,它进入一个int必须被转换为字节。这stikes我奇怪,像 .ReadByte函数()不首先返回一个字节。还有一个原因,为什么MS做了这样?

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());
}

一想到发生在我身上。也许这可以归结为使用。也许 ReadByte()经常被用来获取短的长度,这subsequents得到通过各种长度的检索消耗

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?

推荐答案

这是不特定内存流,而这是因为基类流的设计,之所以说是

This is not specific to Memory stream, rather it is because of the design of base class "Stream" and the reason for that is

返回值:

的无符号字节投为Int32,或-1,如果在流的末尾。

The unsigned byte cast to an Int32, or -1 if at the end of the stream.

-1不能重新presented

-1 cannot be represented using unsigned byte