在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;
}
答案 0 :(得分:4)
不,虽然我偶尔也希望有一个条件返回语句,但该条件返回(基于条件)或方法继续。您可以这样写:
public SomeBaseType MyFunction()
{
return SomeFunction() ?? LocalMethod();
SomeBaseType LocalMethod()
{
// Do lots of other statements...
return somethingElseThatIsADerivedTypeThatDoesntMatter;
}
}
...但是实际上还不清楚。