C# 中的三元运算符

csharpprogrammingserver side programming更新于 2025/9/25 23:07:17

三元运算符是 C# 中的条件运算符。它接受三个参数并计算布尔表达式的值。

例如 −

b = (a == 1) ? 20 : 30;

上面,如果第一个操作数计算结果为真 (1),则计算第二个操作数的值。如果第一个操作数计算结果为假 (0),则计算第三个操作数的值。

下面是一个例子 −

示例

using System;

namespace DEMO {

   class Program {

      static void Main(string[] args) {

         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}

输出

Value of b is 30
Value of b is 20

相关文章