Why does Code Analysis flag me when using the null

2019-07-04 16:37发布

问题:

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;
        }
    }
}