三元运算符的语法:
Condition ? Expression1 : Expression2;
其中表达式中Condition为真,则结果返回Expresson1;如果表达式中Condition为假,则结果返回Expresson2。
三元运算符的例子:
using System;
namespace Operator
{
class Ternary
{
public static void Main(string[] args)
{
int number = 2;
Console.WriteLine((number % 2 == 0) ? true : false);
Console.ReadLine();
}
}
}
结果:
If...else的例子:
using System;
namespace Operator
{
class Ternary
{
public static void Main(string[] args)
{
int number = 2;
bool isEven;
if (number % 2 == 0)
{
isEven = true;
}
else
{
isEven = false;
}
Console.WriteLine(isEven);
Console.ReadLine();
}
}
}
结果:
结论:
三元运算符是 if...else 语句的替代品,两者可以互换。
扩展:
if (a > b)
{
result = "a is greater than b";
}
else if (a < b)
{
result = "b is greater than a";
}
else
{
result = "a is equal to b";
}
等同于下列三元运算符
result = a > b ? "a is greater than b" : a < b ? "b is greater than a" : "a is equal to b";