【发布时间】: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