一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

C#/CShorp switch case 用法

时间:2022-06-25 08:28:24 编辑:袖梨 来源:一聚教程网

C#/CShorp switch 语句是一个控制语句,它通过将控制传递给其体内的一个 case 语句来处理多个选择和枚举
int caseSwitch = 1;
switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}

制传递给与开关的值匹配的 case 语句。switch 语句可以包括任意数目的 case 实例,但是任何两个 case 语句都不能具有相同的值。语句体从选定的语句开始执行,直到 break 将控制传递到 case 体以外。在每一个 case 块(包括上一个块,不论它是 case 语句还是 default 语句)的后面,都必须有一个跳转语句(如 break)。但有一个例外,(与 C++ switch 语句不同)C# 不支持从一个 case 标签显式贯穿到另一个 case 标签。这个例外是当 case 语句中没有代码时

using System;
public enum TimeOfDay {
    Morning = 0,
    Afternoon = 1,
    Evening = 2
}

class EnumExample {
    public static void Main() {
        WriteGreeting(TimeOfDay.Morning);

    }

    static void WriteGreeting(TimeOfDay timeOfDay) {
        switch (timeOfDay) {
            case TimeOfDay.Morning:
                Console.WriteLine("Good morning!");
                break;
            case TimeOfDay.Afternoon:
                Console.WriteLine("Good afternoon!");
                break;
            case TimeOfDay.Evening:
                Console.WriteLine("Good evening!");
                break;
            default:
                Console.WriteLine("Hello!");
                break;
        }
    }
}

与函数一起操作 www.111com.net

using System;

public enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturaday,Sunday };
 
class ConveyorControl {

 
  public void conveyor(Week com) {
    switch(com) {
      case Week.Monday:
        Console.WriteLine("Starting Monday.");
        break;
      case Week.Tuesday:
        Console.WriteLine("Stopping Tuesday.");
        break;
      case Week.Wednesday:
        Console.WriteLine("Moving Wednesday.");
        break;
      case Week.Thursday:
        Console.WriteLine("Moving Thursday.");
        break;
    }
  }
}
 
class MainClass {
  public static void Main() {
    ConveyorControl c = new ConveyorControl();
 
    c.conveyor(Week.Thursday);
    c.conveyor(Week.Tuesday);
    c.conveyor(Week.Wednesday);
    c.conveyor(Week.Monday);
    
  }
}

热门栏目