如何在foreach中处理NullReferenceException?

时间:2010-12-20 08:21:54

标签: c# foreach nullreferenceexception

foreach (string s in myField.getChilds()) {
    if (s == null)
        //handle null
    else
        //handle normal value 
}

当我运行程序时,我得到一个NullReferenceException,因为getChilds可能返回null。如何使程序继续运行并处理异常?我不能在foreach之外处理它,无法解释为什么因为它需要花费太多时间(而且我相信你们很忙:P)。有什么想法吗?

我已经尝试过这种方式:

foreach (string s in myField.getChilds() ?? new ArrayList(1)) {
        if (s == null)
            //handle null
        else
            //handle normal value 
    }

但它不起作用,程序只是跳到foreach的末尾,但我想让它进入foreach而不是!

3 个答案:

答案 0 :(得分:11)

这样做的一种方法(虽然不是最好的方法)是:

foreach (string s in myField.getChilds() ?? new string[] { null })

foreach (string s in myField.getChilds() ?? new ArrayList { null })

new ArrayList(1)不起作用的原因是它创建了一个列表,其中 capacity 可容纳1个元素,但仍为空。但是new string[] { null }创建一个字符串数组,其中只有一个元素,它只是null,这就是你想要的。

答案 1 :(得分:2)

var children = myField.getChilds();
if (children == null)
{
    // Handle the null case
}
else
{
    foreach (string s in children)
    {

    }
}

或只是使用null coalescing operator

foreach (string s in myField.getChilds() ?? Enumerable.Empty<string>())
{

}

答案 2 :(得分:2)

如果是myField.getChilds()可能包含null

foreach (string s in myField.getChilds()) {
if (string.IsNullOrEmpty(s))
    //handle null
else
    //handle normal value 

}

这样,你可以handel null或空字符串。

相关问题