三元運算子/C# 中的條件運算子是什麼?


三元運算子是C#中的條件運算子。它接受三個引數並求值布林表示式。

例如 -

y = (x == 1) ? 70 : 100;

上述操作中,如果第一個運算元計算為真 (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

300 瀏覽量

開啟您的 職業 生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.