Csharp/CSharp Tutorial/Statement/Goto

Материал из .Net Framework эксперт
Версия от 15:20, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Demonstrate the goto.

<source lang="csharp">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!"); 
   
 }  

}</source>

i0
i1
i2
i3
Stopped!

The use of the goto statement in a if statement

<source lang="csharp">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;
   }
 }

}</source>

1
2
3
4

Use goto with a switch

  1. The goto is C#"s unconditional jump statement.
  2. When encountered, program flow jumps to the location specified by the goto.
  3. The goto requires a label for operation.
  4. A label is a valid C# identifier followed by a colon.


<source lang="csharp">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(); 
   } 
 } 

}</source>

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

<source lang="csharp">using System; class MainClass {

 static void Main(string[] args)
 {
   int a = 0;
   while (a < 10)
   {
     if (a == 5)
       goto cleanup;
   }
 cleanup :
   Console.WriteLine(a);
 }

}</source>