MemoryStream: why convert to byte after readByte

£可爱£侵袭症+ 提交于 2019-12-01 14:07:07

问题


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?


回答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:

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

-1 cannot be represented using unsigned byte




回答2:


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 from ReadByte is first byte its not be used in the this fashion, something like

byte[] buff = new byte[ms.Length];
ms.Read(buff , 0, buff .Length);



回答3:


I do believe they are converting with that from int to byte in a reallllllly nice way, since ReadByte() returns an int and their byteArray is of type int[].



来源:https://stackoverflow.com/questions/6868809/memorystream-why-convert-to-byte-after-readbyte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!