关系运算符与逻辑运算符

本教程将详细介绍 C# 中的关系运算符和逻辑运算符及其在条件判断中的使用方法。

1. 关系运算符概述

关系运算符用于比较两个值之间的关系,返回一个布尔值(true 或 false)。关系运算符通常用于条件语句和循环中,以控制程序的执行流程。

2. 关系运算符列表

运算符 描述 示例 结果
== 等于 5 == 3 false
!= 不等于 5 != 3 true
> 大于 5 > 3 true
< 小于 5 < 3 false
>= 大于等于 5 >= 3 true
<= 小于等于 5 <= 3 false

3. 关系运算符的使用

3.1 比较数值

int a = 5;
int b = 3;

bool result1 = a == b; // false
bool result2 = a != b; // true
bool result3 = a > b;  // true
bool result4 = a < b;  // false
bool result5 = a >= b; // true
bool result6 = a <= b; // false

3.2 比较字符串

字符串比较使用字典序(按字符的 Unicode 值比较)。

string str1 = "apple";
string str2 = "banana";

bool result1 = str1 == str2; // false
bool result2 = str1 != str2; // true
bool result3 = str1 > str2;  // false ("apple" 在字典序中小于 "banana")
bool result4 = str1 < str2;  // true

3.3 比较对象

对于引用类型,== 运算符比较的是对象的引用(内存地址),而不是对象的内容。

string s1 = "hello";
string s2 = "hello";
string s3 = new string("hello".ToCharArray());

bool result1 = s1 == s2; // true (字符串池优化)
bool result2 = s1 == s3; // true (字符串的 == 被重写,比较内容)
bool result3 = ReferenceEquals(s1, s3); // false (比较引用)

4. 逻辑运算符概述

逻辑运算符用于组合多个布尔表达式,返回一个布尔值。逻辑运算符主要用于复杂的条件判断。

5. 逻辑运算符列表

运算符 描述 示例 结果
&& 逻辑与(短路) true && false false
|| 逻辑或(短路) true || false true
! 逻辑非 !true false
& 逻辑与(非短路) true & false false
| 逻辑或(非短路) true | false true
^ 逻辑异或 true ^ false true

6. 逻辑运算符的使用

6.1 逻辑与 (&&)

逻辑与运算符要求所有条件都为 true,结果才为 true。如果第一个条件为 false,则不会计算第二个条件(短路评估)。

int age = 25;
bool hasLicense = true;

if (age >= 18 && hasLicense)
{
    Console.WriteLine("可以驾驶");
}
else
{
    Console.WriteLine("不可以驾驶");
}

6.2 逻辑或 (||)

逻辑或运算符只要有一个条件为 true,结果就为 true。如果第一个条件为 true,则不会计算第二个条件(短路评估)。

int score = 85;

if (score >= 90 || score <= 60)
{
    Console.WriteLine("成绩极端");
}
else
{
    Console.WriteLine("成绩正常");
}

6.3 逻辑非 (!)

逻辑非运算符用于反转布尔值。

bool isSunny = false;

if (!isSunny)
{
    Console.WriteLine("今天不是晴天");
}
else
{
    Console.WriteLine("今天是晴天");
}

6.4 非短路逻辑运算符 (&, |)

非短路逻辑运算符会计算所有条件,无论前面的条件是否已经确定了结果。

// 短路逻辑:如果第一个条件为 false,第二个条件不会执行
if (false && DoSomething())
{
    // 不会执行
}

// 非短路逻辑:无论第一个条件如何,第二个条件都会执行
if (false & DoSomething())
{
    // 不会执行,但 DoSomething() 会被调用
}

6.5 逻辑异或 (^)

逻辑异或运算符当两个条件不同时返回 true,相同时返回 false。

bool a = true;
bool b = false;
bool result = a ^ b; // true

bool c = true;
bool d = true;
bool result2 = c ^ d; // false

7. 运算符优先级

当一个表达式中包含多个运算符时,C# 会按照以下优先级顺序执行操作:

优先级 运算符 描述
1 () [] . 括号、数组索引、成员访问
2 ! 逻辑非
3 * / % 乘法、除法、取模
4 + - 加法、减法
5 < <= > >= 关系运算符
6 == != 相等性运算符
7 & 逻辑与(非短路)
8 ^ 逻辑异或
9 | 逻辑或(非短路)
10 && 逻辑与(短路)
11 || 逻辑或(短路)
12 = += -= *= /= %= 赋值运算符

8. 短路评估

注意: 短路评估是指在逻辑运算中,当结果已经可以确定时,不再计算剩余的表达式。这可以提高程序的效率,并避免一些潜在的错误。
// 短路评估示例
int x = 0;

// 由于 x == 0 为 true,不会执行 x++,所以 x 仍然是 0
if (x == 0 || x++ > 0)
{
    Console.WriteLine("条件成立,x = " + x); // 输出: 条件成立,x = 0
}

// 由于 x == 0 为 true,会继续执行 x++,所以 x 变为 1
if (x == 0 | x++ > 0)
{
    Console.WriteLine("条件成立,x = " + x); // 输出: 条件成立,x = 1
}

// 由于 x == 1 为 true,不会执行可能导致除零异常的操作
int y = 0;
if (x == 1 && (10 / y > 0))
{
    // 不会执行到这里,因为 10 / y 会引发异常
}
else
{
    Console.WriteLine("条件不成立"); // 输出: 条件不成立
}

9. 常见错误与注意事项

错误 1:混淆 == 和 =

解决方案:在条件判断中使用 == 进行比较,使用 = 进行赋值。

// 错误示例
if (x = 5) // 这是赋值操作,不是比较,总是返回 true
{
    // 永远会执行
}

// 正确示例
if (x == 5) // 这是比较操作
{
    // 只有当 x 等于 5 时执行
}

错误 2:字符串比较使用 ==

注意:在 C# 中,字符串的 == 运算符已经被重写,用于比较字符串内容,而不是引用。但在其他引用类型中,== 通常比较的是引用。

// 字符串比较(正确)
string s1 = "hello";
string s2 = "hello";
if (s1 == s2) // 比较内容,返回 true
{
    // 执行
}

// 对象比较(比较引用)
object o1 = new object();
object o2 = new object();
if (o1 == o2) // 比较引用,返回 false
{
    // 不执行
}

// 对象内容比较(使用 Equals 方法)
if (o1.Equals(o2)) // 比较内容,返回 false(因为是不同对象)
{
    // 不执行
}

错误 3:逻辑运算符的优先级

解决方案:使用括号明确指定运算顺序,避免依赖默认优先级。

// 可能产生意外结果的示例
if (x > 5 && y < 10 || z == 0) // 优先级:&& 高于 ||
{
    // 执行
}

// 明确指定顺序的示例
if ((x > 5 && y < 10) || z == 0)
{
    // 执行
}

if (x > 5 && (y < 10 || z == 0))
{
    // 执行
}

10. 示例程序

下面是一个完整的示例程序,演示了关系运算符和逻辑运算符的使用:

using System;

namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 关系运算符示例
            int a = 10;
            int b = 5;
            
            Console.WriteLine("关系运算符示例:");
            Console.WriteLine($"a = {a}, b = {b}");
            Console.WriteLine($"a == b: {a == b}");
            Console.WriteLine($"a != b: {a != b}");
            Console.WriteLine($"a > b: {a > b}");
            Console.WriteLine($"a < b: {a < b}");
            Console.WriteLine($"a >= b: {a >= b}");
            Console.WriteLine($"a <= b: {a <= b}");
            
            // 逻辑运算符示例
            bool isSunny = true;
            bool isWarm = false;
            
            Console.WriteLine("\n逻辑运算符示例:");
            Console.WriteLine($"isSunny = {isSunny}, isWarm = {isWarm}");
            Console.WriteLine($"isSunny && isWarm: {isSunny && isWarm}");
            Console.WriteLine($"isSunny || isWarm: {isSunny || isWarm}");
            Console.WriteLine($"!isSunny: {!isSunny}");
            Console.WriteLine($"isSunny ^ isWarm: {isSunny ^ isWarm}");
            
            // 短路评估示例
            int x = 0;
            Console.WriteLine("\n短路评估示例:");
            Console.WriteLine($"初始 x = {x}");
            
            if (x == 0 || x++ > 0)
            {
                Console.WriteLine($"|| 运算后 x = {x}"); // x 仍为 0
            }
            
            x = 0;
            if (x == 0 | x++ > 0)
            {
                Console.WriteLine($"| 运算后 x = {x}"); // x 变为 1
            }
            
            // 综合示例
            Console.WriteLine("\n综合示例:");
            int age = 20;
            bool hasID = true;
            bool hasLicense = false;
            
            if (age >= 18 && hasID)
            {
                if (hasLicense)
                {
                    Console.WriteLine("可以开车");
                }
                else
                {
                    Console.WriteLine("需要先考驾照");
                }
            }
            else
            {
                Console.WriteLine("不满足条件");
            }
            
            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }
    }
}

11. 总结

通过本教程,您应该已经掌握了 C# 中关系运算符和逻辑运算符的使用方法。这些运算符是构建条件语句和循环的基础,对于控制程序的执行流程至关重要。

在使用关系运算符和逻辑运算符时,需要注意以下几点:

  • 关系运算符用于比较两个值,返回布尔值
  • 逻辑运算符用于组合多个布尔表达式
  • 短路评估可以提高程序效率,避免不必要的计算
  • 使用括号明确指定运算顺序,避免依赖默认优先级
  • 注意字符串比较的特殊性,C# 中字符串的 == 比较的是内容

掌握好这些运算符的使用,将帮助您编写更加清晰、高效的 C# 代码。