简体   繁体   中英

ReSharper warning for Possible System.NullReferenceException despite implicit null check

I am getting a ReSharper (2018.1) warning for Possible 'System.NullReferenceException' when I check for null implicitly with if (obj) instead of if (obj ! = null) .

For example:

using JetBrains.Annotations;
using UnityEngine.UI;

public class CanBeNullTest : MonoBehaviour
{
    [CanBeNull] public Button Button { get; set; }

    private void EnableButton_explicitCheck()
    {
        if (Button != null) Button.enabled = true;
    }

    private void EnableButton_implicitCheck()
    {
        if (Button) Button.enabled = true;
    }

    //private void EnableButton_cSharp6()
    //{
    //    // null propagating operator is not available in C# 4
    //    Button?.enabled = true;
    //}
}

Only the implicit null check shows the ReSharper warning:

ReSharper的无效检查警告

I looked at the ReSharper page for "Why is ReSharper suggesting this" and the links there, but I couldn't find an explanation for this.

Is this a ReSharper limitation? Or is it incorrect or bad style to check for null implicitly?

Although it doesn't actually produce a NullReferenceException, because your Button can be null and the if statement triggers an implicit conversion to boolean that produces the NullReferenceException, it is still valid warning in general.

Something similar in Java, Check if null Boolean is true results in exception

If you don't like extra null checks, you may be able to do the C# equivalent of the following Java code,

if (Boolean.TRUE.equals(value)) {...}

if (Button)涉及到bool的隐式转换,在这种情况下不会产生NullReferenceException ,但通常是有效的警告。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM