| 之间有什么区别?和||或者 C# 中的运算符?

来源:这里教程网 时间:2026-02-21 16:14:32 作者:

| 之间有什么区别?和||或者 c# 中的运算符?

| 运算符

| 运算符计算其操作数的逻辑或。如果 x 或 y 之一评估为 true,则 x | y 的结果为 true。否则,结果为 false。

即使左操作数评估为 true,| 运算符也会评估两个操作数,以便操作结果为 true,而不管右操作数的值如何。

|| 运算符

条件逻辑或运算符 ||,也称为“短路”逻辑或运算符,计算其操作数的逻辑或。

如果 x 或 y 之一评估为 true,则 x || y 的结果为 true。否则,结果为 false。如果 x 评估为 true,则不会评估 y。

示例

class Program {
   static void Main(string[] args){
      int a = 4;
      int b = 3;
      int c = 0;
      c = a | b;
      Console.WriteLine("Line 1 - Value of c is {0}", c);
      Console.ReadLine();
   }
}

输出

Value of c is 7
Here the values are converted to binary
4−−100
3−−011
Output 7 −−111

Example 2

的翻译为:

示例2

static void Main(string[] args){
   int a = 4;
   int b = 3;
   int c = 7;
   if (a > b || b > c){
      System.Console.WriteLine("a is largest");
   } else {
      System.Console.WriteLine("a is not largest");
   }
   Console.ReadLine();
}

输出

a is largest

在上面的示例中,其中一个条件返回 true,因此它永远不会检查下一个条件。

相关推荐