简体   繁体   English

做..在C#中循环?

[英]Do .. While loop in C#?

How do I write a Do .. While loop in C#? 如何在C#中编写Do .. While循环?

(Edit: I am a VB.NET programmer trying to make the move to C#, so I do have experience with .NET / VB syntax. Thanks!) (编辑:我是一名VB.NET程序员,试图转向C#,所以我确实有.NET / VB语法的经验。谢谢!)

The general form is: 一般形式是:

do
{
   // Body
} while (condition);

Where condition is some expression of type bool . conditionbool类型的某种表达。

Personally I rarely write do/while loops - for , foreach and straight while loops are much more common in my experience. 就个人而言,我很少写do / while循环 - forforeach和直接while循环在我的经验中更常见。 The latter is: 后者是:

while (condition)
{
    // body
}

The difference between while and do...while is that in the first case the body will never be executed if the condition is false to start with - whereas in the latter case it's always executed once before the condition is ever evaluated. whiledo...while之间的区别在于,在第一种情况下,如果条件为false,则不会执行正文 - 而在后一种情况下,它总是在条件被评估之前执行一次。

Since you mentioned you were coming from VB.NET, I would strongly suggest checking out this link to show the comparisons. 由于您提到您来自VB.NET,我强烈建议您查看此链接以显示比较。 You can also use this wensite to convert VB to C# and vice versa - so you can play with your existing VB code and see what it looks like in C#, including loops and anything else under the son.. 您也可以使用 wensite将VB转换为C#,反之亦然 - 这样您就可以使用现有的VB代码,看看它在C#中的样子,包括循环和儿子下面的任何其他内容。

To answer the loop question, you simple want to do something like: 要回答循环问题,您只需要执行以下操作:

while(condition)
{
   DoSomething();
}

You can also do - while like this: 你也可以这样做 - 虽然这样:

do
{
   Something();
}
while(condition);

Here's another code translator I've used with success, and another great C#->VB comparison website . 这是我成功使用的另一个代码翻译器另一个很棒的C# - > VB比较网站 Good Luck! 祝好运!

//remember, do loop will always execute at least once, a while loop may not execute at all
//because the condition is at the top
do
{
  //statements to be repeated
} while (condition);

Quite surprising that no one has mentioned yet the classical example for the do..while construct. 非常令人惊讶的是,还没有人提到过do..while构造的经典例子。 Do..while is the way to go when you want to run some code, check or verify something (normally depending on what happened during the execution of that code), and if you don't like the result, start over again. 当你想要运行一些代码,检查或验证某些东西时(通常取决于执行该代码期间发生的事情),并且如果你不喜欢结果,请重新开始。 This is exactly what you need when you want some user input that fits some constraints: 当您想要一些符合某些约束条件的用户输入时,这正是您所需要的:

bool CheckInput(string input) { ... }
...
string input;
...
do {
  input=Console.ReadLine();
} while(!CheckInput(input));

That's quite a generic form: when the condition is simple enough, it's common to place it directly on the loop construct (inside the brackets after the "while" keyword), rather than having a method to compute it. 这是一个非常通用的形式:当条件足够简单时,通常将它直接放在循环结构上(在“while”关键字后面的括号内),而不是有一个计算它的方法。

The key concepts in this usage are that you have to request the user input at least once (in the best case, the user will get it right at the first try); 这种用法的关键概念是你必须至少要求用户输入一次(在最好的情况下,用户将在第一次尝试时得到它); and that the condition doesn't really make much sense until the body has executed at least once. 并且在身体至少执行一次之前,条件并没有多大意义。 Each of these are good hints that do..while is the tool for the job, both of them together are almost a guarantee. 这些都是很好的提示,虽然这是工作的工具,但它们在一起几乎是一种保证。

Here's a simple example that will print some numbers: 这是一个打印一些数字的简单示例:

int i = 0;

do {
  Console.WriteLine(++i);
} while (i < 10);
using System;

class MainClass
{
    public static void Main()
    {
        int i = 0;
        do
        {
            Console.WriteLine("Number is {0}", i);
            i++;
        } while (i < 100);
    }
}

Another method would be 另一种方法是

using System;

class MainClass
{
    public static void Main()
    {
        int i = 0;
        while(i <100)
        {
            Console.WriteLine("Number is {0}", i);
            i++;
        }
    }
}

The answer by Jon Skeet is correct and great, though I would like to give an example for those unfamiliar with while and do-while in c#: 由乔恩飞碟双向的答案是正确的,伟大的,但我想举一个例子对于那些不熟悉whiledo-while在C#中:

int i=0;
while(i<10)
{
    Console.WriteLine("Number is {0}", i);
    i++;
}

and: 和:

int i=0;
do
{
    Console.WriteLine("Number is {0}", i);
    i++;
}while(i<10)

will both output: 将输出:

Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9

as we would expect. 正如我们所料。 However it is important to understand that the do-while loop always executes the body the first time regardless of the check. 然而,重要的是要理解do-while循环总是在第一次执行主体而不管检查。 This means that if we change i's starting value to 100 we will see very different outputs. 这意味着如果我们将i的起始值更改为100,我们将看到非常不同的输出。

int i=100;
while(i<10)
{
    Console.WriteLine("Number is {0}", i);
    i++;
}

and: 和:

int i=100;
do
{
    Console.WriteLine("Number is {0}", i);
    i++;
}while(i<10)

Now the while loop actually generates no output: 现在while循环实际上不生成输出:

however the do-while loop generates this: 但是do-while循环生成了这个:

Number is 100

despite being well over 10. This is because of the unique behavior of a do-while loop to always run once unlike a regular while loop. 尽管远远超过10.这是因为do-while循环的独特行为总是运行一次,而不像常规while循环。

Apart from the Anthony Pegram's answer, you can use also the while loop, which checks the condition BEFORE getting into the loop 除了Anthony Pegram的答案之外,你还可以使用while循环,它在进入循环之前检查条件

while (someCriteria)
{
    if (someCondition)
    {
        someCriteria = false;
        // or you can use break;
    }
    if (ignoreJustThisIteration)
    {
        continue;
    }
}

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

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