CA2213 warning when using ?. (null-conditional Operator) to call Dispose

时间秒杀一切 提交于 2019-12-12 09:34:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!