检查如果对象是在C#空 [英] Checking if an object is null in C#

查看:101
本文介绍了检查如果对象是在C#空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想美元对象页上$ pvent进一步的处理,如果它为null。

I would like to prevent further processing on an object if it is null.

在以下code我检查对象为null有两种方法:

In the following code I check if the object is null by either:

if (!data.Equals(null))

if (data != null)

不过,我在收到的NullReferenceException dataList.Add(数据)。如果对象为null,它不应该甚至进入了如果语句来!

However, I receive a NullReferenceException at dataList.Add(data). If the object was null, it should never have even entered the if-statement!

于是,我问这是否是检查的正确方法如果一个对象为空:

Thus, I'm asking if this is proper way of checking if an object is null:

public List<Object> dataList;
public  bool AddData(ref Object data)
    bool success = false;
    try
    {
        // I've also used "if (data != null)" which hasn't worked either
        if (!data.Equals(null))
        {
           //NullReferenceException occurs here ...
           dataList.Add(data);
           success = doOtherStuff(data);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
    return success;
}

如果这是检查的正确方法如果对象是空,我究竟做错了(我怎么能在对象上prevent进一步处理,以避免NullReferenceException异常)?

If this is the proper way of checking if the object is null, what am I doing wrong (how can I prevent further processing on the object to avoid the NullReferenceException)?

推荐答案

这不是数据,但的DataList

您需要创建一个以

public List<Object> dataList = new List<Object>();

更妙的是:因为它是一个领域,使其私人。如果有什么preventing你,让它也只读。刚刚好做法。

Even better: since it's a field, make it private. And if there's nothing preventing you, make it also readonly. Just good practice.

除了

检查无效正确的方法是如果(数据!= NULL)。这种检查是无处不在引用类型;甚至可空&LT; T&GT; 覆盖平等的运营商是前pressing更方便的方法 nullable.HasValue 检查无效时。

The correct way to check for nullity is if(data != null). This kind of check is ubiquitous for reference types; even Nullable<T> overrides the equality operator to be a more convenient way of expressing nullable.HasValue when checking for nullity.

如果您如果(!data.Equals(空))那么你将得到一个的NullReferenceException 如果数据== NULL 。这是因为避免这种例外的是目标摆在首位那种滑稽。

If you do if(!data.Equals(null)) then you will get a NullReferenceException if data == null. Which is kind of comical since avoiding this exception was the goal in the first place.

您也这样做:

catch (Exception e)
{
    throw new Exception(e.ToString());
}

这肯定是不好的。我可以想像,你把它放在那里只是让你可以同时进入调试器仍然是方法,在这种情况下忽略此段落内。否则,不抓白白异常。如果你这样做,只用重新抛出他们扔;

This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don't catch exceptions for nothing. And if you do, rethrow them using just throw;.

这篇关于检查如果对象是在C#空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆