Csharp/CSharp Tutorial/Statement/Goto — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

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

  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.


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);
  }
}