【问题标题】:Is there a single line statement to return from a function only if a conditional is true?仅当条件为真时,是否有从函数返回的单行语句?
【发布时间】:2019-09-29 19:47:09
【问题描述】:

在 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;
}

【问题讨论】:

  • return SomeFunction();
  • 返回 SomeFunction() ??其他函数();
  • 还有别的吗? something == null 是什么?
  • 这个 sn-p 不会编译。你有一个没有返回的代码路径。
  • 您的问题使用minimal reproducible example 会更清楚,但假设您想在条件 满足的情况下继续使用该方法的其余部分,那么不,有没有语法糖。

标签: c# if-statement conditional-statements


【解决方案1】:

不,在方法中没有返回(基于条件)或继续的“条件返回语句”,尽管我偶尔也希望有一个。你可以写:

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

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

...但这真的没有更清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2013-04-19
    • 2020-02-27
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多