简体   繁体   English

C#在中间重启一个while循环

[英]C# restart a while loop in the middle

I have a while loop that i want to restart if a condition is false, in my case. 在我的情况下,如果条件为false,我有一个我想重启的while循环。 It is because i'm checking if a ip is valid and if it is then run the whole loop normal and if not i need it to restart from the start again at that point. 这是因为我正在检查ip是否有效以及是否然后运行整个循环正常,如果不是,我需要它从那时开始重新开始。 I can't use a break and i dont want to use a goto. 我不能使用休息,我不想使用goto。 What is your sugestions? 你的sugestions是什么?

This is my code, where i want to restart my while loop. 这是我的代码,我想重新启动while循环。

while (calculateAgain == "y")
{
    Console.Write("Your ip here: ");
    string ip = Console.ReadLine();

    IpValidation(ip);
    if (IpValidation(ip) == false)
    {
        Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
        // goto or break
    }

After this my code runs on a lot... Tell me some solutions to this other than goto. 在此之后我的代码运行了很多...告诉我除了goto以外的一些解决方案。

You need to use the word continue 你需要使用单词continue

    if (IpValidation(ip) == false)
    {
        Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
        continue;
    }

This will skip the rest and go to the top of your loop. 这将跳过其余部分并转到循环的顶部。

There is the continue statement. 有继续声明。 If it will be hit it will skip back to the start of the loop. 如果它被击中它将跳回到循环的开始。

while (calculateAgain == "y")
{
    // ...
    if (IpValidation(ip) == false)
    {
        Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
        continue;
    }
    Console.WriteLine("This will not be executed when continue is called");
}

You can do this on two ways, (by using break or continue) break will exit the loop completely, continue will just skip the current iteration. 您可以通过两种方式执行此操作(通过使用break或continue)break将完全退出循环, continue将跳过当前迭代。

So by reading your question. 所以通过阅读你的问题。 You need to use continue here, so your example might look like this: 你需要在这里continue使用,所以你的例子可能如下所示:

while (calculateAgain == "y")
{
    Console.Write("Your ip here: ");
    string ip = Console.ReadLine();

    IpValidation(ip);
    if (IpValidation(ip) == false)
    {
        Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
        continue;
    }
}

This above means, for condition if (IpValidation(ip) == false) code below will be skiped (will never be executed) if condition is satisfied 上面的意思是,对于条件if (IpValidation(ip) == false)下面的代码将被满足(如果满足条件,将永远不会被执行)

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

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