?: ?? Operators Instead Of IF|ELSE

前端 未结 9 1655
粉色の甜心
粉色の甜心 2020-11-28 02:09
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
                


        
9条回答
  •  悲哀的现实
    2020-11-28 02:55

    The ternary operator RETURNS one of two values. Or, it can execute one of two statements based on its condition, but that's generally not a good idea, as it can lead to unintended side-effects.

    bar ? () : baz();
    

    In this case, the () does nothing, while baz does something. But you've only made the code less clear. I'd go for more verbose code that's clearer and easier to maintain.

    Further, this makes little sense at all:

    var foo = bar ? () : baz();
    

    since () has no return type (it's void) and baz has a return type that's unknown at the point of call in this sample. If they don't agree, the compiler will complain, and loudly.

提交回复
热议问题