0

我有来自开源 c# 程序的这段代码。

我试图弄清楚这个片段背后的目的。

internal static bool ReadAsDirectoryEntry(BinaryReader br)
    {
        bool dir;

        br.BaseStream.Seek(8, SeekOrigin.Current);
        dir = br.ReadInt32() < 0;
        br.BaseStream.Seek(-12, SeekOrigin.Current);

        return dir;
    }

我不清楚第 6 行的代码,谁能解释它的作用?布尔值如何具有返回的 int32 且小于零的值?

谢谢!

4

4 回答 4

7

您读取一个 int 并检查该 int 是否小于 0。表达式br.ReadInt32() < 0将导致 bool。您分配给变量的这个布尔结果。

于 2013-08-14T11:15:22.873 回答
2
internal static bool ReadAsDirectoryEntry(BinaryReader br)
{
    bool dir;

    // Skip 8 bytes starting from current position
    br.BaseStream.Seek(8, SeekOrigin.Current);

    // Read next bytes as an Int32 which requires 32 bits (4 bytes) to be read 
    // Store whether or not this integer value is less then zero
    // Possibly it is a flag which holds some information like if it is a directory entry or not
    dir = br.ReadInt32() < 0;

    // Till here, we read 12 bytes from stream. 8 for skipping + 4 for Int32
    // So reset stream position to where it was before this method has called
    br.BaseStream.Seek(-12, SeekOrigin.Current);

    return dir;
}
于 2013-08-14T11:19:51.750 回答
1

基本上,这在逻辑上等同于(但更简洁):

bool dir;
int tmp = br.ReadInt32();
if(tmp < 0)
{
    dir = true;
}
else
{
    dir = false;
}

它:

  • 是否调用ReadInt32()(这将导致int
  • 测试结果是否是< 0(这将导致trueor false
  • 并将结果(truefalse)分配给dir

基本上,true 当且仅当调用ReadInt32()给一个负数时它才会返回。

于 2013-08-14T11:15:12.890 回答
0

第 6 行的意思是:读取一个 Int32,然后将其与 0 进行比较,然后将比较结果存储到一个布尔值中。

它相当于:

Int32 tmp = br.ReadInt32();
dir =  tmp < 0;
于 2013-08-14T11:17:04.880 回答