在 C# 中,比较运算符用于比较两个值之间的关系,并返回一个布尔值(true 或 false)。
int a = 5;
int b = 3;
bool isEqual = a == b;
Console.WriteLine(isEqual); // 输出 false
string str1 = "Hello";
string str2 = "Hello";
bool isStringEqual = str1 == str2;
Console.WriteLine(isStringEqual); // 输出 true
int a = 5;
int b = 3;
bool isNotEqual = a != b;
Console.WriteLine(isNotEqual); // 输出 true
string str1 = "Hello";
string str2 = "World";
bool isStringNotEqual = str1 != str2;
Console.WriteLine(isStringNotEqual); // 输出 true
int a = 5;
int b = 3;
bool isGreater = a > b;
Console.WriteLine(isGreater); // 输出 true
string str1 = "Hello";
string str2 = "World";
bool isStringGreater = str1 > str2;
Console.WriteLine(isStringGreater); // 输出 false
int a = 5;
int b = 3;
bool isLess = a < b;
Console.WriteLine(isLess); // 输出 false
string str1 = "Hello";
string str2 = "World";
bool isStringLess = str1 < str2;
Console.WriteLine(isStringLess); // 输出 true
int a = 5;
int b = 3;
bool isGreaterOrEqual = a >= b;
Console.WriteLine(isGreaterOrEqual); // 输出 true
string str1 = "Hello";
string str2 = "Hello";
bool isStringGreaterOrEqual = str1 >= str2;
Console.WriteLine(isStringGreaterOrEqual); // 输出 true
int a = 5;
int b = 3;
bool isLessOrEqual = a <= b;
Console.WriteLine(isLessOrEqual); // 输出 false
string str1 = "Hello";
string str2 = "World";
bool isStringLessOrEqual = str1 <= str2;
Console.WriteLine(isStringLessOrEqual); // 输出 true
以上是 C# 中常用的比较运算符及其示例代码。您可以使用这些运算符对变量、常量或表达式进行比较,并根据比较结果执行相应的逻辑。比较运算符对于控制流程和条件语句的判断非常有用。