C# 中的三元運算子


三元運算子是 C# 中的條件運算子。它需要三個引數並評估布林表示式。

例如 −

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

上述示例中,如果第一個運算元評估為 true (1),則會評估第二個運算元。如果第一個運算元評估為 false (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.