?:?? 运算符而不是IF | ELSE

Ahm*_*eim 84 c# ternary-operator

public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以将?: ??运营商完全用作If/Else吗?


我的问题:
如何编写以下内容?:?? 运营商

[1]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
Run Code Online (Sandbox Code Playgroud)

[2]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
} 
Run Code Online (Sandbox Code Playgroud)

简单地说:如何做什么,什么也不做,并与?: ??操作员做多个指令?

tru*_*ity 193

对于[1],您不能:这些运算符返回值,而不执行操作.

表达方式

a ? b : c
Run Code Online (Sandbox Code Playgroud)

求值bif a为true,求值cif a为false.

表达方式

b ?? c
Run Code Online (Sandbox Code Playgroud)

求值为bif b不为null并求值为cif b为null.

如果你写

return a ? b : c;
Run Code Online (Sandbox Code Playgroud)

要么

return b ?? c;
Run Code Online (Sandbox Code Playgroud)

他们总会回报一些东西.

对于[2],您可以编写一个函数来返回执行"多个操作"的正确值,但这可能比仅使用更糟糕if/else.


Oli*_*rth 41

三元运算符(?:)不是为控制流而设计的,它仅用于条件赋值.如果需要控制程序的流程,请使用控制结构,例如if/ else.

  • 我将补充说,我已经看到人们使用嵌套的三元表达式来代替if/else,它会产生难以阅读和调试的代码.周围的恶魔. (5认同)
  • 如果正确使用空格,有时嵌套的三元运算符会产生更易读的代码. (4认同)
  • @truth:是的,我没有反对嵌套的`?:`本身.但我有一个很大的问题,他们被用于控制流,尤其是*嵌套*控制流! (2认同)

Akr*_*hda 11

指的?:运算符(C#参考)

条件运算符(?:)根据布尔表达式的值返回两个值中的一个.以下是条件运算符的语法.

参考?? 运算符(C#参考)

?? ?? operator被称为null-coalescing运算符,用于为可空值类型和引用类型定义默认值.如果它不为null,则返回左侧操作数; 否则返回正确的操作数.

这意味着:

[第1部分]

return source ?? String.Empty;
Run Code Online (Sandbox Code Playgroud)

[第2部分]不适用......

  • 这与什么都不做有所不同.它返回一个空字符串. (3认同)