C#条件语句 -0011

条件语句

C#拥有两个条件语句的构造器:

  • if语句可以用来判断指定条件是否满足;
  • switch语句则比较表达式可能产生的多个结果值,switch / case 语句提供了一种更方便的多分支条件选择;

if语句

using System;

namespace Wrox
{
    internal class Program
    {
        private static void Main()
        {
            Console.WriteLine("Type in a string");

            string input;
            input = Console.ReadLine();

            if (input == "")
            {
                Console.WriteLine("You typed in an empty string.");
            }
            else if (input.Length < 5)
            {
                Console.WriteLine("The string had less than 5 characters.");
            }
            else if (input.Length < 10)
            {
                Console.WriteLine(
                "The string had at least 5 but less than 10 Characters.");
            }
            Console.WriteLine("The string was " + input);
        }
    }
}

注意:作为if的判断条件,只能是true或者false或者返回true/false的表达式,C#不允许使用整型代替。

Switch语句

switch (integerA)
{
	case 1:
		Console.WriteLine("integerA = 1");
		break;
	case 2:
		Console.WriteLine("integerA = 2");
		break;
	case 3:
		Console.WriteLine("integerA = 3");
                Console.WriteLine("integerA is not 1 or 2.");
		break;
	default:
		Console.WriteLine("integerA is not 1, 2, or 3");
		break;
}

  • 当任何case都不满足表达式条件时,就会进入default里执行;
  • case之后的值必须是常量,不能是表达式,也不能是任何变量;
  • C#可以将2个或者多个case语句进行同一种处理
switch(country)
{
	case "au":
	case "uk":
	case "us":
		language = "English";
		break;
	case "at":
	case "de":
		language = "German";
		break;
}

  

原文地址:https://www.cnblogs.com/codesee/p/13033204.html