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" );
    }
}

我可以将?: ??运算符像If/Else一样使用吗?

我的问题:
如何用?编写以下内容:运算符(operator)

[1]
if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[2]
if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

简要地:如何使用?:??运算符不执行任何操作,不返回任何内容并执行多个指令?

最佳答案

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

表达方式

a ? b : c

如果b为true,则求值为a;如果c为false,则求值为a

表达方式
b ?? c

如果b不为null,则求值为b;如果c为null,则求值为b

如果你写
return a ? b : c;

要么
return b ?? c;

他们将永远返回一些东西。

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

10-08 08:27
查看更多