Csharp/CSharp Tutorial/Statement/Goto
Содержание
Demonstrate the goto.
using System;
class MainClass {
public static void Main() {
for(int i=0; i < 10; i++) {
Console.WriteLine("i" + i);
if(i == 3)
goto stop;
}
stop:
Console.WriteLine("Stopped!");
}
}
i0 i1 i2 i3 Stopped!
The use of the goto statement in a if statement
class MainClass
{
public static void Main()
{
int total = 0;
int counter = 0;
myLabel:
counter++;
total += counter;
if (counter < 5)
{
System.Console.WriteLine(counter);
goto myLabel;
}
}
}
1 2 3 4
Use goto with a switch
- The goto is C#"s unconditional jump statement.
- When encountered, program flow jumps to the location specified by the goto.
- The goto requires a label for operation.
- A label is a valid C# identifier followed by a colon.
using System;
class SwitchGoto {
public static void Main() {
for(int i=1; i < 5; i++) {
switch(i) {
case 1:
Console.WriteLine("In case 1");
goto case 3;
case 2:
Console.WriteLine("In case 2");
goto case 1;
case 3:
Console.WriteLine("In case 3");
goto default;
default:
Console.WriteLine("In default");
break;
}
Console.WriteLine();
}
}
}
In case 1 In case 3 In default In case 2 In case 1 In case 3 In default In case 3 In default In default
While with goto statement
using System;
class MainClass
{
static void Main(string[] args)
{
int a = 0;
while (a < 10)
{
if (a == 5)
goto cleanup;
}
cleanup :
Console.WriteLine(a);
}
}