(原创)c#学习笔记04--流程控制03--分支03--switch语句

4.3.3 switch语句

  switch 语句非常类似于if 语句,因为它也是根据测试的值来有条件地执行代码。但是,switch语句可以一次将测试变量与多个值进行比较,而不是仅测试一个条件。这种测试仅限于离散的值,而不是像“大于X”这样的子句,所以它的用法有点不同,但它仍是一种强大的技术。

  switch语句的基本结构如下:

    switch (<testVar>)

    {

    case <comparisonVal1>:

      <code to execute if <testVar> == <comparisonVal1> >

      break;

    case <comparisonVal2>:

      <code to execute if <testVar> == <comparisonVal2> >

      break;

    ...

    case <comparisonValN>:

      <code to execute if <testVar> == <comparisonValN> >

      break;

    default:

      <code to execute if <testVar> != comparisonVals>

      break;

    }

  <testVar>中的值与每个<comparisonValX>值(在case语句中指定)进行比较,如果有一个匹配,就执行为该匹配提供的语句。如果没有匹配,就执行default部分中的代码。

  执行完每个部分中的代码后,还需有另一个语句break。在执行完一个case块后,再执行第二个case语句是非法的。

  这里的break语句将中断switch语句的执行,而执行该结构后面的语句。

  note: 在此,C#与C++是有区别的,在C++中,可以在运行完一个case语句后,运行另一个case语句。

  在C#代码中,还有一种方法可以防止程序流程从一个case语句转到下一个case语句。即使用return语句中断当前函数的运行,而不是仅中断switch结构的执行(详见第6章)。也可以使用goto语句(如前所述),因为case语句实际上是在C#代码中定义的标签。

  一个case语句处理完后,不能自由进入下一个case语句,但这个规则有一个例外。如果把多个case 语句放在一起(堆叠它们),其后加一个代码块,实际上是一次检查多个条件。如果满足这些条件中的任何一个,就会执行代码,例如:

    switch (<testVar>)

    {

    case <comparisonVal1>:

    case <comparisonVal2>:

      <code to execute if <testVar> == <comparisonVal1> or <testVar> == <comparisonVal2> >

      break;

    ...
  注意,这些条件也应用到default语句。

  每个<comparisonValX>都必须是一个常数值。一种方法是提供字面值

switch (myInteger) 
{ 
case 1: 
  <code to execute if myInteger == 1> 
  break; 
case -1: 
  <code to execute if myInteger == -1> 
  break; 
default: 
  <code to execute if myInteger != comparisons> 
  break; 
} 

  另一种方式是使用常量。常量与其他变量一样,但有一个重要的区别:它们包含的值是固定不变的

  声明常量需要指定变量类型和关键字const,同时必须给它们赋值。

const int intTwo = 2; 

  如果编写如下代码:

const int intTwo; 
intTwo = 2; 

  就会产生一个编译错误。如果在最初的赋值之后,试图通过任何方式改变常量的值,也会出现编译错误

  下面演示下switch语句使用示例,代码如下:

static void Main(string[] args) 
{ 
  const string myName = "karli"; 
  const string sexyName = "angelina"; 
  const string sillyName = "ploppy"; 
  string name; 
  Console.WriteLine("What is your name?"); 
  name = Console.ReadLine(); 
  switch (name.ToLower()) 
  { 
  case myName: 
    Console.WriteLine("You have the same name as me!"); 
    break; 
  case sexyName: 
    Console.WriteLine("My, what a sexy name you have!"); 
    break; 
  case sillyName: 
    Console.WriteLine("That’s a very silly name."); 
    break; 
  } 
  Console.WriteLine("Hello {0}!", name); 
  Console.ReadKey(); 
} 

  运行结果如下:

原文地址:https://www.cnblogs.com/wodehao0808/p/4896203.html