C#布尔运算、条件和switch语句

本文介绍C#代码中的布尔运算、比较运算、?:运算符、if语句和switch语句结构。

布尔运算

布尔运算又称为逻辑运算,参与运算的值包括true(真)和false(假),在C#中使用bool关键字定义布尔类型变量和常量,对应的.NET Farmework类型是Boolean结构。布尔运算包括:

  • 与运算,使用&&或&运算符。需要两个运算数,当两个运算数都是true时,运算结果为true,否则运算结果是false。&&和&运算符的不同点在于,使用&&运算符时,如果左表达式为false则不再计算右表达式的值,直接返回运算结果false;而&运算符总是会计算两个表达式的值。此外,&运算符还可以用作整数的位与运算。
  • 或运算,使用||或|运算符。需要两个运算数,当两个运算数中有一个是true时,运算结果为true,两个运算数都是false时,运算结果为false。||与|运算符的区别在于,使用||运算符时,左表达式的值为true时不再计算右表达式的值,直接返回运算果true;|运算符总是计算两个表达式的值。此外,|运算符还用于整数的位或运算。
  • 异或运算,使用^运算符。需要两个运算数,当两个运算数不同时,运算结果为true,相同时运算结果为false。^运算符也用于整数的位异或运算。
  • 取反运算,使用!运算符。true取反得false,false取反得true。!运算符也可以用于整数的位取反运算。

下面的代码演示了基本的布尔运算。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            bool x = true, y = false;
            Console.WriteLine(x && y);  // False
            Console.WriteLine(x && x);  // True
            Console.WriteLine(x || y);  // True
            Console.WriteLine(x | y);  // True
            Console.WriteLine(x ^ y);  // True
            Console.WriteLine(!x);  // Fase
        }
    }
}

比较运算

C#中的比较运算包括:

  • 等于,使用==运算符。
  • 不等于,使用!=运算符。
  • 大于,使用>运算符。
  • 大于等于,使用>=运算符。
  • 小于,使用<运算符。
  • 小于等于,使用<=运算符。

比较运算中,当比较结果成立时,运算结果为true,比较结果不成立时,运算结果为false。下面的代码演示了比较运算的基本应用。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10, y = 99;
            Console.WriteLine(x == y);  // False
            Console.WriteLine(x != y);  // True
            Console.WriteLine(x > y);  // False
            Console.WriteLine(x >= y);  // False
            Console.WriteLine(x < y);  // True
            Console.WriteLine(x <= y);  // True
        }
    }
}

?:运算符

?:运算符是三元运算符,需要三个表达式,如x?y:z中,当x表达式的值是true时,运算结果为y,x表达式的值是false时,运算结果为z。下面的代码演示了?:运算符的基本应用。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10, y = 99;
            Console.WriteLine(x >= y ? x : y);  // 99
            Console.WriteLine(x <= y ? x : y);  // 10
        }
    }
}

if语句

先来看if语句的基本结构。

C#
if (<条件1>) 
{
    <语句1>
}
else if (<条件2>)
{
    <语句2>
}
else if (<条件3>)
{
    <语句3>
}
else
{
    <语句n>
}

在此结构中,如果<条件1>成立(true)则执行<语句1>,否则,如果<条件2>成立则执行<语句2>,否则,如果<条件3>成立则执行<语句3>;所有条件都不成立时执行<语句n>。这里,<条件1>和<语句1>是必须的,else if语句可以没有,也可以有一个或多个;else语句可以没有也可以有一个,使用时应在else if语句的后面,一般会使用else语句处理所有条件之外的情况。

下面的代码演示了简单的if语句结构。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            if (x % 2 == 0) Console.WriteLine("{0}是偶数", x);
        }
    }
}

代码的功能是判断变量x的值是否为偶数,如果是偶数则显示信息。下面的代码会在不是偶数时也进行提示。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 9;
            if (x % 2 == 0) Console.WriteLine("{0}是偶数", x);
            else Console.WriteLine("{0}不是偶数", x);
        }
    }
}

如示例中所示,满足条件的语句如果只有一条,可以将语句直接写在if、else或else if语句同一行。

下面的代码会判断年份是否为闰年。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int year = 2000;
            if (year % 400 == 0 ||
                (year % 100 != 0 && year % 4 == 0))
            {
                Console.WriteLine("{0}年是闰年", year);
            }
            else
            {
                Console.WriteLine("{0}年不是闰年", year);
            }
        }
    }
}

执行代码会显示“2000年是闰年”,可以修改变量year的值来观察执行结果。

下面的代码会显示指定年份中的某月有多少天。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int year = 2000;
            int month = 2;
            int daysInMonth = -1;
            if (month == 1 || month == 3 || month == 5 ||
                month == 7 || month == 8 || month == 10 || month == 12)
            {
                daysInMonth = 31;
            }
            else if (month == 4 || month == 6 || month == 9 || month == 11)
            {
                daysInMonth = 30;
            }
            else if (month == 2)
            {
                daysInMonth = IsLeap(year) ? 29 : 28;
            }
            //
            if (daysInMonth > 0)
                Console.WriteLine("{0}年{1}月有{2}天", year, month, daysInMonth);
            else
                Console.WriteLine("无效的日期数据");
        }
        //
        static bool IsLeap(int year)
        {
            return year % 400 == 0 ||
                (year % 100 != 0 && year % 4 == 0);
        }
    }
}

执行代码会显示“2000年2月有29天”,可以修改变量year和month的值来观察执行结果。代码中,将判断闰年的代码封装为IsLeap()方法,方法中直接返回了闰年条件的判断的结果。请注意,在第一个if语句结构中,由于已经给daysInMonth变量设置了默认值-1,所有没有使用else语句处理month变量为其它值的情况。

实际工作中,可以使用DateTime.IsLeapYear()静态方法判断年份是否为闰年,使用DateTime.DaysInMonth()静态方法获取指定年份中某月的天数。

switch语句

switch语句适合于条件只有一个表达式,并根据表达式不同的值分别执行对应代码的情况,应用结构如下。

C#
switch(<表达式>)
{
    case <值1>:
        <语句1>
    case <值2>:
        <语句2>
    case <值3>:
        <语句3>
    default:
        <语句n>
}

结构中,当<表达式>的值是<值1>时执行<语句1>,<值2>时执行<语句2>,<值2>时执行<语句3>,没有对应的值时执行<语句n>。需要注意的是,case和default语句都有向下贯穿的特性,需要终止执行时应使用break或return语句,如下面的代码会利用贯穿特性判断指定年中的某月有多少天。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int year = 2000;
            int month = 2;
            int daysInMonth = -1;
            switch(month)
            {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    daysInMonth = 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    daysInMonth = 30;
                    break;
                case 2:
                    daysInMonth = DateTime.IsLeapYear(year) ? 29 : 28;
                    break;
            }
            //
            if (daysInMonth > 0)
                Console.WriteLine("{0}年{1}月有{2}天", year, month, daysInMonth);
            else
                Console.WriteLine("无效的日期数据");
        }
    }
}

代码中,当month值为1、3、5、7、8、10时没有执行代码,会向下贯穿到case 12语句,此时将daysInMonth设置为31,并使用break语句终止switch语句结构;同样的,当month值为4、6、9时也没有执行代码,会向下贯穿到case 11语句,此时将daysInMonth设置为30,并使用break语句终止switch语句结构;最后,当month为2时,根据year值是否为闰年分别指定天数据,同样需要使用break语句终止switch语句结构。这里,因为已经给daysInMonth变量设置了默认值-1,所以,并没有使用default语句处理month为其它值的情况。

switch语句结构中,default语句的位置是没有限制的,如下面的代码。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string colorName = "red";
            string cnName = "";
            switch(colorName)
            {
                default:
                    cnName="不知道的颜色";
                    break;
                case "red":
                    cnName = "红色";
                    break;
                case "blue":
                    cnName = "蓝色";
                    break;
                case "green":
                    cnName = "绿色";
                    break;
            }
            //
            Console.WriteLine(cnName);
        }
    }
}

本例,可以修改colorName的内容来观察执行结果。实际工作中,习惯上会将default语句放在所有case语句结构之后,如下面的代码。

C#
using System;

namespace csfx_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string colorName = "red";
            string cnName = "";
            switch(colorName)
            {
                case "red":
                    cnName = "红色";
                    break;
                case "blue":
                    cnName = "蓝色";
                    break;
                case "green":
                    cnName = "绿色";
                    break;
                default:
                    cnName="不知道的颜色";
                    break;
            }
            //
            Console.WriteLine(cnName);
        }
    }
}