如何使`for`循环像`while`循环一样工作?

时间:2012-05-18 06:41:48

标签: c# for-loop while-loop

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

我有这个代码工作:

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

我需要此for循环的while等效项。

到目前为止,我有这个:

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

4 个答案:

答案 0 :(得分:4)

每次使用其中一种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

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

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

循环1:

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

循环2:

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

我认为你可以从这里解决剩下的问题。

答案 3 :(得分:0)

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);
}