简体   繁体   English

C#for循环语法

[英]C# for loop syntax

I'm working on some C# code that has loop syntax that I've never seen before: 我正在研究一些C#代码,它具有我以前从未见过的循环语法:

for (;;)
{
  //Do some stuff
}

What does a for loop without a init; 没有init;的for循环是什么init; condition; or increment do? increment呢? By the way it's really hard to find meaningful search results on the internet for "for (;;) c# " on any search engine I tried. 顺便说一下,在我试过的任何搜索引擎上,为了"for (;;) c# ”在互联网上找到有意义的搜索结果真的很难。

-Eric -Eric

That is an infinite loop . 这是一个infinite loop Like you stated, it will run until a part of it breaks (throws an exception or otherwise exists the loop) or the machine runs out of resources to support the loop. 就像你说的那样,它会一直运行,直到它的一部分中断(抛出异常或以其他方式存在循环)或者机器耗尽资源来支持循环。

for (;;)
{
   //do stuff
} 

Is just the same as: 与以下相同:

do
{
   //do stuff
}while (true)

while(true)
{
   //do stuff
}

The syntax of a for loop is thus: 因此, for循环的语法是:

for (condition; test; action)

Any one of those items can be omitted (per the language spec). 可以省略这些项目中的任何一个(根据语言规范)。 So what you've got is an infinite loop. 所以你得到的是无限循环。 A similar approach: 类似的方法:

while (true) { // do some stuff }

for (;;)

Short answer : It is an infinite loop which is equivalent to while(true) 简答 :这是一个无限循环,相当于while(true)

Long answer : for (initializer; condition; iterator) Structure of the for statement 答案很长for (initializer; condition; iterator) for语句的结构

  • initializer block: Do not initialize variable. 初始化块:不初始化变量。
  • condition block: with no condition (means execute infinitely) => while true 条件块:没有条件(表示无限执行)=> true
  • iterator block: with no operation to any variable (no iterator) 迭代器块:对任何变量都没有操作(没有迭代器)

for(;;) example from official documentation for(;;)来自官方文档的示例

This type of for loop is an infinite loop. 这种类型的for循环是一个无限循环。 It is the equivalent of while(true){stuff to be executed...} . 它相当于while(true){stuff to be executed...} It keeps on going until it hits a break, return, or a goto to a label outside the loop. 它会继续运行,直到它达到中断,返回或转到循环外的标签。

A for loop has three parts, an initialization, a condition, and a block to be executed after the loop. for循环有三个部分,初始化,条件和循环后要执行的块。 Without a condition to be tested against, the loop will just keep on going. 如果没有要测试的条件,循环将继续进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM