问题
I'm implementing IDisposable
, and in my Dispose()
method when calling Dispose()
on other managed resources I'm using the ?.
operator like so:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(disposing)
{
_ChangeLock?.Dispose();
}
}
I'm still getting the following 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 I change to a standard null check, the code analysis warning goes away:
if(_ChangeLock != null)
_ChangeLock.Dispose();
Is there something wrong with using the null-conditional operator the way I am, or is this code analysis rule outdated, or what?
回答1:
This is a known issue with FxCop.
It appears they have 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.
来源:https://stackoverflow.com/questions/36229230/ca2213-warning-when-using-null-conditional-operator-to-call-dispose