常量条件¶
ID: cs/constant-condition
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- maintainability
- readability
- external/cwe/cwe-835
Query suites:
- csharp-security-and-quality.qls
始终计算结果为 true
或始终计算结果为 false
的条件可以删除,从而简化程序逻辑。如果条件是循环条件,请考虑使用有界迭代重写循环(例如,foreach
循环),如果可能的话。
建议¶
尽可能避免使用常量条件,并消除这些条件或替换它们。
示例¶
在以下示例中,条件 a > a
始终为假,因此 Max(x, y)
始终返回 x
。
class Bad
{
public int Max(int a, int b)
{
return a > a ? a : b;
}
}
修改后的示例将条件替换为 a > b
。
class Good
{
public int Max(int a, int b)
{
return a > b ? a : b;
}
}