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

Mat*_*ith 1 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;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

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

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

    SomeBaseType LocalMethod()
    {  
        // Do lots of other statements...
        return somethingElseThatIsADerivedTypeThatDoesntMatter;
    }
}
Run Code Online (Sandbox Code Playgroud)

……但实际上还不清楚。