?: ?? Operators Instead Of IF|ELSE

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


        
9条回答
  •  佛祖请我去吃肉
    2020-11-28 02:39

    For [1], you can't: these operators are made to return a value, not perform operations.

    The expression

    a ? b : c
    

    evaluates to b if a is true and evaluates to c if a is false.

    The expression

    b ?? c
    

    evaluates to b if b is not null and evaluates to c if b is null.

    If you write

    return a ? b : c;
    

    or

    return b ?? c;
    

    they will always return something.

    For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.

提交回复
热议问题