简体   繁体   English

SqlDataReader while(reader.Read())

[英]SqlDataReader while(reader.Read())

private bool ReadMagic(BinaryReader reader) 
{ 
     try 
     { 
          ini: 

          byte b0 = reader.ReadByte(); 
          if (b0 != 0xF9) goto ini; 

          b0 = reader.ReadByte(); 
          if (b0 != 0xbe) goto ini; 

          b0 = reader.ReadByte(); 
          if (b0 != 0xb4) goto ini; 

          b0 = reader.ReadByte(); 
          if (b0 != 0xd9) goto ini; 

          return true; 
     } 
     catch (EndOfStreamException) 
     { 
          return false; 
     } 
}

I found this piece of code on github and was wondering why someone would use the ReadMagic function instead of the usual reader.Read() function? 我在github上找到了这段代码,想知道为什么有人会使用ReadMagic函数而不是通常的reader.Read()函数? Also could someone explain how the ReadMagic function works? 还可以有人解释ReadMagic函数的工作原理吗?

using(var reader = command.ExecuteReader())
{
     while(ReadMagic(reader));
}

A SqlDataReader is very much not the same thing as a BinaryReader , and you wouldn't use it as such. SqlDataReaderBinaryReader几乎是不一样的,您不会这样使用它。 The BinaryReader is for reading streams (eg reading from a file). BinaryReader用于读取流(例如,从文件读取)。 It has methods such as ReadByte , used here, for reading actual bytes from the stream, whereas SqlDataReader uses Read to advance to the next returned row, if there is one. 它具有ReadByte方法,用于从流中读取实际字节,而SqlDataReader使用Read前进到返回的下一行(如果有的话)。

It looks like the ReadMagic function is consuming bytes from the stream until it gets a series of 0xF9, 0xBE, 0xB4, 0xD9 - presumably some sort of marker in whatever stream it happens to be reading, then returning true upon finding it. 看起来ReadMagic函数正在消耗流中的字节,直到它获得一系列0xF9、0xBE,0xB4、0xD9-大概是它正在读取的任何流中的某种标记,然后在找到它时返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM