设置属性时未使用属性值¶
ID: cs/unused-property-value
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- maintainability
- language-features
Query suites:
- csharp-security-and-quality.qls
忽略分配给属性的值会导致混淆并导致意外结果。类的用户期望根据分配给属性的值获得不同的结果,但当忽略该值时,就不会发生这种情况。
通常在以下三种情况下会发生这种情况
该属性不应被赋值。在这种情况下,调用者期望赋值会产生一些影响,但实际上并没有。
该属性使用
bool
表示特定状态。在这种情况下,调用者可能期望将属性设置为false
与将其设置为true
会产生不同的效果。该属性是虚拟的或重写的。在这种情况下,某些派生类可以使用该属性,而其他类则忽略它。因此,结果中排除了虚拟属性和重写属性。
建议¶
应删除空 setter(主体为空的 set
)。
如果 setter 不使用赋值,请将 set
替换为不带参数的方法。或者,更改 set
的实现以使用赋值,或者在赋值无效时抛出异常。
示例¶
以下示例显示了 set
忽略赋值的两种情况。在第一种情况下,该属性不支持 set
,因此实现为空。在第二种情况下,set
代码对所有赋值具有相同的效果。
class Window
{
const int screenWidth = 1280;
int x0, x1;
public int Width
{
get { return x1 - x0; }
// BAD: Setter has no effect
set { }
}
public bool FullWidth
{
get { return x0 == 0 && x1 == screenWidth; }
// BAD: This is confusing if value==false
set { x0 = 0; x1 = screenWidth; }
}
}
第一个问题可以通过简单地删除空的 set
来解决。第二个问题可以通过在方法中而不是在属性中实现功能来解决。
class Window
{
const int screenWidth = 1280;
int x0, x1;
public int Width
{
get { return x1 - x0; }
}
public bool IsFullWidth
{
get { return x0 == 0 && x1 == screenWidth; }
}
public void MakeFullWidth()
{
x0 = 0; x1 = screenWidth;
}
}
参考¶
MSDN,C# 编程指南:使用属性。