仅当条件为true时,才从函数返回单行语句吗?

时间:2019-05-12 18:41:32

标签: c# if-statement conditional-statements

在C#中,是否有任何语法糖可以在单个语句(基本上是有条件的返回)中执行以下操作:

public SomeBaseType MyFunction()
{
    // Can the two statements below be combined into one?
    SomeBaseType something = SomeFunction();
    if ( something != null ) { return something; }
    // End of statements regarding this question.


    // Do lots of other statements...
    return somethingElseThatIsADerivedTypeThatDoesntMatter;
}

1 个答案:

答案 0 :(得分:4)

不,虽然我偶尔也希望有一个条件返回语句,但该条件返回(基于条件)或方法继续。您可以这样写:

public SomeBaseType MyFunction()
{
    return SomeFunction() ?? LocalMethod();

    SomeBaseType LocalMethod()
    {  
        // Do lots of other statements...
        return somethingElseThatIsADerivedTypeThatDoesntMatter;
    }
}

...但是实际上还不清楚。