使用 ? 时出现 CA2213 警告。 (空条件运算符)调用 Dispose
CA2213 warning when using ?. (null-conditional Operator) to call Dispose
我正在实施 IDisposable
,在我的 Dispose()
方法中调用 Dispose()
其他托管资源时,我正在使用 ?.
运算符,如下所示:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(disposing)
{
_ChangeLock?.Dispose();
}
}
我仍然收到以下内容code analysis error:
CA2213: 'MyClass' contains field 'MyClass._ChangeLock' that is of IDisposable type: 'ReaderWriterLockSlim'. Change the Dispose method on 'MyClass' to call Dispose or Close on this field.
如果我更改为标准空检查,代码分析警告就会消失:
if(_ChangeLock != null)
_ChangeLock.Dispose();
是我这样使用空条件运算符有问题,还是这个代码分析规则过时了,还是什么?
这是一个带有 FxCop 的 known issue。
看来他们有 decided not to fix it:
We decided to cut [CA2213] because it is very hard to get it right without deeper analysis, tracking variables and possibly having annotations. The current implementation is very noisy and has a lot of false positives and the value of the rule is not worth all the noise it generates.
我正在实施 IDisposable
,在我的 Dispose()
方法中调用 Dispose()
其他托管资源时,我正在使用 ?.
运算符,如下所示:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(disposing)
{
_ChangeLock?.Dispose();
}
}
我仍然收到以下内容code analysis error:
CA2213: 'MyClass' contains field 'MyClass._ChangeLock' that is of IDisposable type: 'ReaderWriterLockSlim'. Change the Dispose method on 'MyClass' to call Dispose or Close on this field.
如果我更改为标准空检查,代码分析警告就会消失:
if(_ChangeLock != null)
_ChangeLock.Dispose();
是我这样使用空条件运算符有问题,还是这个代码分析规则过时了,还是什么?
这是一个带有 FxCop 的 known issue。
看来他们有 decided not to fix it:
We decided to cut [CA2213] because it is very hard to get it right without deeper analysis, tracking variables and possibly having annotations. The current implementation is very noisy and has a lot of false positives and the value of the rule is not worth all the noise it generates.