首页 > 代码库 > C# MemoryStream先写后读的奇怪现象

C# MemoryStream先写后读的奇怪现象

static void Main(string[] args)
        {
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);

            int ix0 = 0x12341314;//注意
            int ix1 = 2;
            bw.Write(ix0);
            bw.Write(ix1);
            //bw.Flush();
            //bw.Close();
            byte[] bes = ms.GetBuffer();

            Console.WriteLine(bes.Length);
            
            //-------------------------------------FLAG-------------------------------------
            BinaryReader br = new BinaryReader(new MemoryStream(bes));//FLAG1:这样写可以正确读取
            //BinaryReader br = new BinaryReader(ms);//FLAG2:这样写会使下面的读取出现异常
            //-------------------------------------FLAG-------------------------------------

            //大小端测试-CPU寄存器存储超过一个字节的数据的存放顺序
            //若是小端,依次输出:0x14, 0x13, 0x34, 0x12
            //若是大端,依次输出: 0x12, 0x34, 0x13, 0x14
            int x0 = br.ReadByte();//如果采用FLAG2代码,这里出现异常:无法在流的结尾之外进行读取
            int x1 = br.ReadByte();
            int x2 = br.ReadByte();
            int x3 = br.ReadByte();
            int x4 = br.ReadByte();

        }

 

C# MemoryStream先写后读的奇怪现象