C# 中的三元运算符


三元运算符是 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

更新于: 20-6-2020

3K+ 浏览量

开启您的职业生涯

完成课程并进行认证

开始
广告
© . All rights reserved.