Skip to content

C# - 关系运算符

什么是关系运算符和相等运算符?

Section titled “什么是关系运算符和相等运算符?”

关系运算符和相等运算符用于比较两个操作数并确定它们之间的关系。比较的结果始终是布尔值:true 或 false。这些运算符是使用 if 语句、while 循环和其他控制结构来控制程序流程的基础。

下表显示了 C# 支持的所有关系运算符和相等运算符。假设 int score = 95; 和 int passingScore = 70;。

运算符名称描述示例
==等于检查两个操作数的值是否相等。(score == 95) 为 true。
!=不等于检查两个操作数的值是否不相等。(score != passingScore) 为 true。
>大于检查左操作数的值是否大于右操作数。(score > passingScore) 为 true。
<小于检查左操作数的值是否小于右操作数。(score < passingScore) 为 false。
>=大于或等于检查左操作数的值是否大于或等于右操作数。(score >= 95) 为 true。
<=小于或等于检查左操作数的值是否小于或等于右操作数。(score <= passingScore) 为 false。

这些运算符的主要用途是在 if-else 块中做出决策。

using System;
int temperature = 25;
if (temperature > 30)
{
Console.WriteLine("It's a hot day!");
}
else if (temperature < 10)
{
Console.WriteLine("It's a cold day!");
}
else
{
Console.WriteLine("The weather is pleasant.");
}
// 输出: The weather is pleasant.

关系运算符对于控制循环的终止条件至关重要。

using System;
// 只要 'i' 小于或等于 5,这个循环就会一直执行。
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Iteration: {i}");
}
// 输出:
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4
// Iteration: 5

理解 == 运算符在不同类型上的行为至关重要:

  • 对于值类型(如 int、double、bool、struct),== 比较它们的实际值。
  • 对于大多数引用类型(如自定义 class),== 比较它们的内存地址(引用)。它检查两个变量是否指向完全相同的对象,而不是它们的内容是否相同。
public record Person(string Name, int Age);
// 值类型比较(structs 或 records)
var p1 = new Person("Alice", 30);
var p2 = new Person("Alice", 30);
Console.WriteLine(p1 == p2); // 输出: true (对于 records), false (对于 classes)
// 引用类型比较(classes)
var list1 = new List<int> { 1, 2 };
var list2 = new List<int> { 1, 2 };
var list3 = list1;
Console.WriteLine(list1 == list2); // 输出: false (内存中不同的对象)
Console.WriteLine(list1 == list3); // 输出: true (指向相同的对象)

注意:string 类型是一个特殊的引用类型,其中 == 被重载以比较内容,在相等性检查时表现得像值类型。

  • 使用 == 进行比较,而不是 =:单个等号(=)是赋值运算符。if (x = 5) 是一个常见的错误;它将 5 赋值给 x,并且在条件语句中可能不会如你所期望地工作。
  • 使用 Equals() 进行对象内容比较:要检查两个不同对象是否具有相同的值(值相等),请在你的类中重写 Equals() 方法,或使用 record 类型,record 类型会自动为你完成此操作。
  • 明确字符串比较方式:对于不区分大小写的字符串比较,不要将两个字符串都转换为小写/大写。使用更高效和清晰的 string.Equals(other, StringComparison.OrdinalIgnoreCase)。
  • 避免冗余的布尔比较:不要写 if (isValid == true),直接写 if (isValid)。不要写 if (isComplete == false),写 if (!isComplete)。

关系运算符经常用于验证。

using System;
Console.WriteLine("Please enter your age:");
string input = Console.ReadLine() ?? "";
if (int.TryParse(input, out int age))
{
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not yet eligible to vote.");
}
}
else
{
Console.WriteLine("That is not a valid age.");
}