Csharp/C Sharp/Language Basics/Switch — различия между версиями

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

Текущая версия на 11:39, 26 мая 2010

Demonstrate the switch

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate the switch. 
 
using System; 
 
public class SwitchDemo {   
  public static void Main() { 
    int i; 
 
    for(i=0; i<10; i++) 
      switch(i) { 
        case 0:  
          Console.WriteLine("i is zero"); 
          break; 
        case 1:  
          Console.WriteLine("i is one"); 
          break; 
        case 2:  
          Console.WriteLine("i is two"); 
          break; 
        case 3:  
          Console.WriteLine("i is three"); 
          break; 
        case 4:  
          Console.WriteLine("i is four"); 
          break; 
        default:  
          Console.WriteLine("i is five or more"); 
          break; 
      } 
      
  }   
}


Empty cases can fall through

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Empty cases can fall through. 
 
using System; 
 
public class EmptyCasesCanFall {   
  public static void Main() { 
    int i; 
 
    for(i=1; i < 5; i++)  
      switch(i) { 
        case 1: 
        case 2: 
        case 3: Console.WriteLine("i is 1, 2 or 3"); 
          break; 
        case 4: Console.WriteLine("i is 4"); 
          break; 
      } 
 
  } 
}


Illustrates the use of the switch statement

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example4_5.cs illustrates the use of
  the switch statement
*/
public class Example4_5
{
  public static void Main()
  {
    int planetPosition = 4;  // Mars
    switch (planetPosition)
    {
      case 1:
        System.Console.WriteLine("Mercury");
        break;
      case 2:
        System.Console.WriteLine("Venus");
        break;
      case 3:
        System.Console.WriteLine("Earth");
        break;
      case 4:
        System.Console.WriteLine("Mars");
        break;
      case 5:
        System.Console.WriteLine("Jupiter");
        break;
      case 6:
        System.Console.WriteLine("Saturn");
        break;
      case 7:
        System.Console.WriteLine("Uranus");
        break;
      case 8:
        System.Console.WriteLine("Neptune");
        break;
      case 9:
        System.Console.WriteLine("Pluto");
        break;
      default:
        System.Console.WriteLine("Planet unknown");
        break;
    }
  }
}


Illustrates the use of the switch statement to compare string values

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example4_6.cs illustrates the use of
  the switch statement to compare string values
*/
public class Example4_6
{
  public static void Main()
  {
    string planetName = "Saturn";  // sixth planet from the Sun
    switch (planetName)
    {
      case "Mercury":
        System.Console.WriteLine(1);
        break;
      case "Venus":
        System.Console.WriteLine(2);
        break;
      case "Earth":
        System.Console.WriteLine(3);
        break;
      case "Mars":
        System.Console.WriteLine(4);
        break;
      case "Jupiter":
        System.Console.WriteLine(5);
        break;
      case "Saturn":
        System.Console.WriteLine(6);
        break;
      case "Uranus":
        System.Console.WriteLine(7);
        break;
      case "Neptune":
        System.Console.WriteLine(8);
        break;
      case "Pluto":
        System.Console.WriteLine(9);
        break;
      default:
        System.Console.WriteLine("Planet unknown");
        break;
    }
  }
}


Simulate a conveyor belt

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Simulate a conveyor belt 
 
using System; 
 
class ConveyorControl { 
  // enumerate the conveyor commands 
  public enum action { start, stop, forward, reverse }; 
 
  public void conveyor(action com) { 
    switch(com) { 
      case action.start: 
        Console.WriteLine("Starting conveyor."); 
        break; 
      case action.stop: 
        Console.WriteLine("Stopping conveyor."); 
        break; 
      case action.forward: 
        Console.WriteLine("Moving forward."); 
        break; 
      case action.reverse: 
        Console.WriteLine("Moving backward."); 
        break; 
    } 
  } 
} 
 
public class ConveyorDemo { 
  public static void Main() { 
    ConveyorControl c = new ConveyorControl(); 
 
    c.conveyor(ConveyorControl.action.start); 
    c.conveyor(ConveyorControl.action.forward); 
    c.conveyor(ConveyorControl.action.reverse); 
    c.conveyor(ConveyorControl.action.stop); 
     
  } 
}


Switch based console menu

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
namespace nsSwitch
{
    using System;
    public class nsSwitch
    {
        static void Main ()
        {
            bool done = false;
            do
            {
                clsAnimal dog = new clsAnimal (1);
                clsAnimal cat = new clsAnimal (2);
                clsAnimal goldfish = new clsAnimal (3);
                clsAnimal aardvark = new clsAnimal (4);
                Console.WriteLine ("Select one of the following:");
                Console.WriteLine ("\t1 -- For dogs");
                Console.WriteLine ("\t2 -- For cats");
                Console.WriteLine ("\t3 -- For goldfish");
                Console.WriteLine ("\t4 -- For aardvarks");
                Console.Write ("Enter Your selection (0 to exit): ");
                string strSelection = Console.ReadLine ();
                int iSel;
                try
                {
                    iSel = int.Parse(strSelection);
                }
                catch (FormatException)
                {
                    Console.WriteLine ("\r\nWhat?\r\n");
                    continue;
                }
                Console.WriteLine ("You selected  " + iSel);
                switch (iSel)
                {
                    case 0:
                        done = true;
                        break;
                    case 1:
                        Console.WriteLine (dog);
                        break;
                    case 2:
                        Console.WriteLine (cat);
                        break;
                    case 3:
                        Console.WriteLine (goldfish);
                        break;
                    case 4:
                        Console.WriteLine (aardvark);
                        break;
                    default:
                        Console.WriteLine ("You selected an invalid number: {0}\r\n", iSel);
                        continue;
                }
                Console.WriteLine ();
            } while (!done);
            Console.WriteLine ("\nGoodbye!");
        }
    }
    class clsAnimal
    {
        public clsAnimal (int Type)
        {
            PetType = Type;
        }
        private int Type;
        public int PetType
        {
            get {return (Type);}
            set {Type = value;}
        }
        public override string ToString()
        {
             switch (PetType)
             {
                 default:
                     return ("Unknown pet");
                 case 1:
                     return ("Your pet type is a dog");
                 case 2:
                     return ("Your pet type is a cat");
                 case 3:
                     return ("Your pet type is a goldfish");
                 case 4:
                     return ("Your pet type is an aardvark");
             }
         }
    }
}


Switch for int type

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_4___Program_Control
{
  public class MyMainClass1
  {
    static void Main(string[] args)
    {
      int a = 0;
      Console.ReadLine();
      switch (a)
      {
        case 1:
          Console.WriteLine("One");
          break;
        case 2:
          Console.WriteLine("Two");
          break;
        default:
          Console.WriteLine("?");
          break;
      }
    }
  }
}


Switch statement containing a branch with no statements: causes a "fall-through" to the next branch

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example4_7.cs illustrates the use of
  the switch statement containing a branch
  with no statements: causes a "fall-through"
  to the next branch
*/
public class Example4_7
{
  public static void Main()
  {
    int value = 1;
    switch (value)
    {
      case 0:
        System.Console.WriteLine("Zero");
        break;
      case 1:
      case 2:
        System.Console.WriteLine("One or two");
        break;
      case 3:
        System.Console.WriteLine("Three");
        break;
      default:
        System.Console.WriteLine("Other number");
        break;
    }
  }
}


Switch Values

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 public class SwitchValues
 {
     static void Main()
     {
         const int Democrat = 0;
         const int Republican = 1;
         const int Progressive = 2;
         // hard wire to Republican
         int myChoice = Republican;
         // switch on the value of myChoice
         switch (myChoice)
         {
             case Democrat:
                 Console.WriteLine("You voted Democratic.");
                 break;
             case Republican:
                 Console.WriteLine("You voted Republican.");
                 break;
             case Progressive:
                 Console.WriteLine("You voted Progressive.");
                 break;
         }
         Console.WriteLine("Thank you for voting.");
     }
 }


Switch Values Fall Through

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
public class ValuesFallThrough
 {
     static void Main()
     {
         String myChoice = "NewLeft";
         // switch on the string value of myChoice
         switch (myChoice)
         {
             case "NewLeft":
                 Console.WriteLine(
                  "The NewLeft members are voting Democratic.");
                 goto case "Democrat";
             case "Democrat":
                 Console.WriteLine("You voted Democratic.\n");
                 break;
             case "CompassionateRepublican": // fall through
             case "Republican":
                 Console.WriteLine("You voted Republican.\n");
                 Console.WriteLine("Don"t you feel compassionate?");
                 break;
             case "Progressive":
                 Console.WriteLine("You voted Progressive.\n");
                 break;
             default:
                 Console.WriteLine("You did not make a valid choice.");
                 break;
         }
         Console.WriteLine("Thank you for voting.");
     }
 }


Switch With Default Values

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
public class SwitchWithDefaultValues
 {
     static void Main()
     {
         const int Democrat = 0;
         const int Republican = 1;
         const int Progressive = 2;
         // hard wire to Republican
         int myChoice = 5;
         // switch on the value of myChoice
         switch (myChoice)
         {
             case Democrat:
                 Console.WriteLine("You voted Democratic.\n");
                 break;
             case Republican:
                 Console.WriteLine("You voted Republican.\n");
                 break;
             case Progressive:
                 Console.WriteLine("You voted Progressive.\n");
                 break;
             default:
                 Console.WriteLine("You did not make a valid choice.");
                 break;
         }
         Console.WriteLine("Thank you for voting.");
     }
 }


Use a char to control the switch

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a char to control the switch. 
 
using System; 
 
public class SwitchDemo2 {   
  public static void Main() { 
    char ch; 
 
    for(ch="A"; ch<= "E"; ch++) 
      switch(ch) { 
        case "A":  
          Console.WriteLine("ch is A"); 
          break; 
        case "B":  
          Console.WriteLine("ch is B"); 
          break; 
        case "C":  
          Console.WriteLine("ch is C"); 
          break; 
        case "D":  
          Console.WriteLine("ch is D"); 
          break; 
        case "E":  
          Console.WriteLine("ch is E"); 
          break; 
      }     
  }   
}