And*_*nea 0 c# if-statement preferences
我有时会用
if (this._currentToolForeColor.HasValue)
return this._currentToolForeColor.Value;
else
throw new InvalidOperationException();
Run Code Online (Sandbox Code Playgroud)
其他时候我用
if (this._currentToolForeColor.HasValue)
return this._currentToolForeColor.Value;
throw new InvalidOperationException();
Run Code Online (Sandbox Code Playgroud)
我知道,这两个是等价的,但我不确定哪个是最好的,为什么.
这更进一步,因为您可以使用其他执行控制语句,如刹车或继续:
while(something)
{
if(condition)
{
DoThis();
continue;
}
else
break;
}
Run Code Online (Sandbox Code Playgroud)
与
while(something)
{
if(condition)
{
DoThis();
continue;
}
break;
}
Run Code Online (Sandbox Code Playgroud)
编辑1:是的循环示例很糟糕,因为它们是合成的(即:弥补这个问题)不同于第一个实际的.
早早失败.
在方法的顶部进行验证,如果超过它,则可以使用(相对)安全性中的值.
public void SomeFunction(object someParameter)
{
if (someParameter == null) throw new ArgumentNullException("someParameter", "Value cannot be null");
// Use the parameter here for stuff
SomeOtherFunction(someParameter, Whichway.Up);
}
Run Code Online (Sandbox Code Playgroud)
这同样适用于该return声明.如果您的方法已经完成,请不要将内容包装在大型if语句中,只需return离开那里即可.
有关此概念的其他示例,请参阅降低圈复杂度.请注意,在我的示例中,只有一个代码路径,这只是您可以使用给定参数获得多远的问题.嵌套的ifs和大括号(即使你不使用大括号,如你的例子中)对可读性的影响也大于你的例子之间的差异.
| 归档时间: |
|
| 查看次数: |
265 次 |
| 最近记录: |