使用三元运算符而不是IF那么有什么意义呢?

l--*_*''' 8 c#

为什么让事情变得更复杂?为什么这样做:

txtNumerator.Text = 
     txtNumerator.Text == "" ? "0" : txtNumerator.Text;
Run Code Online (Sandbox Code Playgroud)

而不是这个:

if txtNumerator.Text="" {txtNumerator.Text="0";}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 32

假设你想要将零或txtNumerator.Text传递给方法M.你会怎么做?

你可以说:

string argument;
if (txtNumerator.Text == "")
{
    argument = "0";
}
else
{
    argument = txtNumerator.Text;
}
M(argument);
Run Code Online (Sandbox Code Playgroud)

或者你可以说

M(txtNumerator.Text == "" ? "0" : txtNumerator.Text);
Run Code Online (Sandbox Code Playgroud)

后者更短,更容易阅读.

这里更重要的一点是语句对于它们的副作用很有用,并且表达式对它们的很有用.如果你想要做的是控制两个副作用中的哪一个发生,那么使用"if"语句.如果你想要做的是控制从两种可能性中选择哪个值,那么考虑使用条件表达式.

更新:

珍妮问为什么不这样做呢?

if (txtNumerator.Text == "")
{
    M("0");
}
else
{
    M(txtNumerator.Text);
}
Run Code Online (Sandbox Code Playgroud)

如果只有一个条件需要检查,那就没关系了.但是,如果有四个呢?现在有十六种可能性,为它编写"if"语句至少可以说是混乱的:

if (text1.Text == "")
{
    if (text2.Text == "")
    {
        if (text3.Text == "")
        {
            if (text4.Text == "")
            {
                M("1", "2", "3", "4");
            }
            else
            {
                M("1", "2", "3", text4.Text);
            }
        }
        else
        {
            if (text4.Text == "")
            {
                M("1", "2", text3.Text, "4");
            }
            else
            {
                M("1", "2", text3.Text, text4.Text);
            }
        }
        ... about fifty more lines of this.
Run Code Online (Sandbox Code Playgroud)

相反,你可以说:

M(Text1.Text == "" ? "1" : Text1.Text,
  Text2.Text == "" ? "2" : Text2.Text,
  Text3.Text == "" ? "3" : Text3.Text,
  Text4.Text == "" ? "4" : Text4.Text);
Run Code Online (Sandbox Code Playgroud)

  • *[条件运算符](http://blogs.msdn.com/b/ericlippert/archive/2010/02/18/whats-the-difference-between-ternary-and-tertiary.aspx)*在以下情况下也很有用你想在派生类型的初始化期间调用基类构造函数,你需要传递从参数计算的值:`class Foo:Bar {Foo(string txt):base(txt ==""?"0" :txt)}` - 例如.您也可以编写静态成员来执行此操作,但在这种情况下使用`?:`会更方便. (6认同)
  • @LBushkin提出了一个很好的观点.在C#中有许多上下文,其中*语句*是非法的,但*表达式*是合法的.在某些情况下,您希望能够表达做出选择的概念,但"if"语句不可用,因为它是一个声明. (5认同)

mqp*_*mqp 8

它是一个表达式,因此您可以直接在赋值或函数调用中使用结果,而无需复制您正在使用它的上下文.这使得许多使用场景的写入和读取都更加清晰.例如:

int abs = (x >= 0) ? x : -x;
Run Code Online (Sandbox Code Playgroud)

int abs;
if (x >= 0)
    abs = x;
else
    abs = -x;
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这是一个关键点.你可以主观论证哪种方法在美学上更具吸引力,而且很多将取决于具体情况,但是如果能够简单地将单独的声明声明和指配声明短路,则很有意义.最终,三元操作扮演的角色不同于'if',因为'if'对于创建单独的代码分支很有用,而'?' 对于获得特定值很有用. (3认同)