C#代码说明

时间:2013-08-14 11:12:43

标签: c# boolean code-snippets

我从开源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;
    }

LINE 6上的代码对我来说不清楚,任何人都可以解释它的作用吗? bool如何具有返回的int32的值并且小于零?

谢谢!

4 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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;
}

答案 2 :(得分:1)

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

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

有:

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

基本上,当且仅当对true的调用给出负数时,它才会返回ReadInt32()

答案 3 :(得分:0)

第6行表示:读取Int32然后将其与0进行比较,然后将比较结果存储为布尔值。

它等同于:

Int32 tmp = br.ReadInt32();
dir =  tmp < 0;