C#代码解释
本文关键字:解释 代码 | 更新日期: 2023-09-27 18:27:41
我有一段来自开源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行的代码,有人能解释一下它的作用吗?bool怎么可能有一个返回的int32值并且小于零?
谢谢!
读取一个int并检查该int是否小于0。表达式br.ReadInt32() < 0
将导致布尔。您分配给变量的这个布尔结果。
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;
}
基本上,即在逻辑上等价于(但比):
bool dir;
int tmp = br.ReadInt32();
if(tmp < 0)
{
dir = true;
}
else
{
dir = false;
}
它:
- 调用
ReadInt32()
(这将导致int
) - 测试其结果是否为
< 0
(将产生true
或false
) - 并将该结果(
true
或false
)分配给dir
基本上,当且仅当对ReadInt32()
的调用给出负数时,它将返回true
。
第6行的意思是:读取Int32,然后将其与0进行比较,然后将比较结果存储为布尔值。
相当于:
Int32 tmp = br.ReadInt32();
dir = tmp < 0;