如何使“for”循环像“while”循环一样工作

本文关键字:循环 一样 工作 何使 for while | 更新日期: 2023-09-27 18:34:29

我知道有一种方法可以让for循环像while循环一样工作。

我有这段代码工作:

while (BR.BaseStream.Position < BR.BaseStream.Length) // BR = BinaryReader
{
    int BlockLength = BR.ReadInt32();
    byte[] Content = BR.ReadBytes(BlockLength);
}

我需要这个while循环的for等效物。

到目前为止,我有这个:

for (long Position = BR.BaseStream.Position; Position < BR.BaseStream.Length; //Don't Know This)
{
    int BlockLength = BR.ReadInt32();
    byte[] Content = BR.ReadBytes(BlockLength);
}

如何使“for”循环像“while”循环一样工作

每次使用 Read 方法之一时,BinaryReader 都会递增它的位置,因此您实际上不需要该部分中的任何内容。

for (long Position = BR.BaseStream.Position; Position < BR.BaseStream.Length; Position = BR.BaseStream.Position)
{
    int BlockLength = BR.ReadInt32();
    byte[] Content = BR.ReadBytes(BlockLength);
}

更新:我刚刚意识到Position变量永远不会更新。您可以在 for 循环的末尾或第三部分中更新它。我更新了代码以更新 for 循环第三部分中的Position

我不确定你为什么要这样做,但这就是你的 for 循环应该是什么样子的

int i = 0;
for (; true; )
{
    Console.WriteLine(i);
    if(++i==10)
        break;
}

在伪代码中,这两个循环是等效的:

循环 1:

Type t = initialiser;
while (t.MeetsCondition())
{
  // Do whatever
  t.GetNextValue();
}

循环 2:

for (Type t = initialiser; t.MeetsCondition(); t.GetNextValue())
  // Do whatever

我认为你可以从这里解决其余的问题。

for (long Position = BR.BaseStream.Position; Position < BR.BaseStream.Length; /* If you Don't Know     This, dont specify this. It is Optionl and can be kept blank */)
{
  int BlockLength = BR.ReadInt32();
  byte[] Content = BR.ReadBytes(BlockLength);
}