简体   繁体   English

空检查对于非空值返回true

[英]Null check returns true for non-null value

Having an odd problem. 有一个奇怪的问题。 It's happened a few times over the years, but I've never been able to figure out why. 这些年来已经发生过几次,但是我一直无法弄清楚为什么。 Always solved it by rearranging the code I had in place, but would like to know is there's a more proper way of dealing with it, or at least figuring out what's behind it. 总是通过重新排列我已有的代码来解决它,但是想知道有没有更合适的方法来处理它,或者至少弄清楚它背后的原因。

Non-working version: 非工作版本:

public bool CaptureFrame(ArrayCache cache)
{
    if (cache == null)
        throw new ArgumentNullException("cache");

    DataArray frame = cache.CacheData;

    if (frame == null)
        throw new ArgumentNullException("cache.CacheData");


    // do stuff
}

Working version: 工作版本:

public bool CaptureFrame(ArrayCache cache)
{
    if (cache == null)
        throw new ArgumentNullException("cache");

    if (cache.CacheData == null)
        throw new ArgumentNullException("cache.CacheData");

    DataArray frame = cache.CacheData;


    // do stuff
}

The problem is this: frame is not null (at least according to the debugger, and by any measure I can trace of the code), however when it does the if (frame == null) check, it comes out true and throws the exception. 问题是这样的:frame 不为空(至少根据调试器,并且无论如何我都可以跟踪代码),但是当它进行if (frame == null)检查时,它为true并抛出例外。 I rewrote to check cache.CacheData and it works fine, but it really shouldn't make any difference to the code logic. 我重写了检查cache.CacheData的方法,它可以正常工作,但实际上对代码逻辑没有任何影响。

I managed to find one other question on the site with a similar problem, which ended up being related to the == and != operators being overloaded. 我设法在站点上找到一个类似问题的另一个问题,该问题最终与==和!=运算符被重载有关。 Those operators are not overloaded for the class in question in my code, and it's a standalone class so there's nothing for it to inherit. 这些运算符不会在我的代码中针对所涉及的类进行重载,并且它是一个独立的类,因此没有任何要继承的类。

Edit: John Saunders requested code for the CacheData property: 编辑:约翰·桑德斯(John Saunders)请求CacheData属性的代码:

private DataArray cacheData;

public DataArray CacheData
{
    get
    {
        return cacheData;
    }
    set
    {
        cacheData = value;
    }
}

looks like you are mapping the exception in the non working one then calling DataArray frame = cache.CacheData; 看起来您正在将异常映射到无法正常工作的异常中,然后调用DataArray frame = cache.CacheData; but what if cache.CacheData if null then you are assigning it to DataFrame.. it's always best in my opinion to do the Check for null first before assigning or assuming your second one looks fine.. prehaps instead of throwing an exception maybe you could trap the exception and try some test cases for both scenarios 但是如果cache.CacheData如果为null呢,那么您要将其分配给DataFrame。.我认为,最好总是先执行Check for null,然后再分配或假设您的第二个看起来不错。.也许不抛出异常,也许捕获异常并针对两种情况尝试一些测试用例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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