C# 中的三元运算符是什么?
csharpprogrammingserver side programming更新于 2025/10/14 10:37:17
三元运算符是 C# 中的条件运算符。它接受三个参数并计算布尔表达式的值。
例如 −
y = (z == 1) ? 100 : 180;
上面,如果第一个操作数计算结果为真 (1),则计算第二个操作数的值。如果第一个操作数计算结果为假 (0),则计算第三个操作数的值。
下面是一个例子 −
示例
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int x, y;
x = 25;
y = (x == 25) ? 20 : 30;
Console.WriteLine("Value of x = {0}", y);
y = (x == 1) ? 50 : 90;
Console.WriteLine("Value of y = {0}", y);
Console.ReadLine();
}
}
}
上面我们有两个使用三元运算符的条件 −
y = (x == 25) ? 20 : 30; y = (x == 1) ? 50 : 90;

