可以组合嵌套的“if”语句¶
ID: cs/nested-if-statements
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- maintainability
- language-features
Query suites:
- csharp-security-and-quality.qls
当两个 if
语句都没有 else
部分时,无需嵌套它们。可以通过将语句组合成单个 if
语句来更简单地编写代码。
建议¶
将 if
语句组合成单个 if
语句。使用 &&
运算符组合条件。
务必检查运算符优先级,并在必要时在每个条件周围使用括号。
示例¶
此示例显示了两个嵌套的 if
语句。
if(connection.Status == Connected)
{
if(!connection.Authenticated)
{
connection.SendAuthRequest();
}
}
由于两个语句都没有 else
部分,因此可以按如下方式重写代码
if(connection.Status == Connected && !connection.Authenticated)
{
connection.SendAuthRequest();
}
参考¶
MSDN:if-else(C# 参考)。
MSDN:C# 运算符。