Why does Code Analysis flag me when using the null conditional operator with Dispose()?

前提是你 提交于 2019-12-10 19:22:59

问题


I have a class that implements IDisposable. I changed my Dispose() method from this:

public void Dispose()
{
    if (AccountCreateResetEvent != null)
    {
        AccountCreateResetEvent.Dispose();
        AccountCreateResetEvent = null;
    }
}

to this:

public void Dispose()
{
    AccountCreateResetEvent?.Dispose();
    AccountCreateResetEvent = null;
}

Now I get the following error when running Code Analysis:

'Adapter' contains field 'Adapter.AccountCreateResetEvent' that is of IDisposable type: 'AutoResetEvent'. Change the Dispose method on 'Adapter' to call Dispose or Close on this field.

Is this a quirk of Code Analysis or am I doing something wrong here?

EDIT: Simple full class declaration that reproduces the problem

using System;
using System.Threading;

namespace IDisposableProblem1
{
    public sealed class Account : IDisposable
    {
        private AutoResetEvent AccountResetEvent = new AutoResetEvent(false);

        public void Dispose()
        {
            AccountResetEvent?.Dispose();
            AccountResetEvent = null;
        }
    }
}

来源:https://stackoverflow.com/questions/34094381/why-does-code-analysis-flag-me-when-using-the-null-conditional-operator-with-dis

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