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.