0

我知道有一种方法可以使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

4 回答 4

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 循环结束时或在第三部分更新它。Position我在 for 循环的第三部分更新了要更新的代码。

于 2012-05-18T06:45:47.773 回答
3

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

int i = 0;
for (; true; )
{
    Console.WriteLine(i);
    if(++i==10)
        break;
}
于 2012-05-18T06:45:57.020 回答
0

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

循环 1:

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

循环 2:

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

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

于 2012-05-18T06:46:45.440 回答
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);
}
于 2012-05-18T06:50:59.937 回答