【问题标题】:How to make a `for` loop work like a `while` loop?如何使“for”循环像“while”循环一样工作?
【发布时间】:2012-05-18 06:41:48
【问题描述】:

我知道有一种方法可以让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);
}

【问题讨论】:

  • 您为什么要这样做?为什么不使用 while 外观本身?
  • @dwerner 不是作业,因为这是我最近的项目!实际上我想将所有while 循环转移到for 循环
  • 没有真正的目的,IMO while 循环比 for 循环更具可读性。
  • @I.am.WritZ 正如罗伯特所说,没有真正的理由,为什么你应该这样做。

标签: c# for-loop while-loop


【解决方案1】:

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

【讨论】:

  • 谢谢,我就是在找这个!!
  • 这是 5 分钟后的答案!
【解决方案2】:

我不知道你为什么要这样做,但你的 for 循环应该是这样的

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

【讨论】:

    【解决方案3】:

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

    循环 1:

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

    循环 2:

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

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

    【讨论】:

      【解决方案4】:
      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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-03
        • 1970-01-01
        • 2016-07-12
        • 2021-07-27
        • 2018-07-24
        • 2019-11-10
        • 1970-01-01
        相关资源
        最近更新 更多