gpt4 book ai didi

c# - 如何处理 foreach 中的 NullReferenceException?

转载 作者:太空狗 更新时间:2023-10-29 20:57:27 25 4
gpt4 key购买 nike

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 而不是!

最佳答案

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

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

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

new ArrayList(1) 不起作用的原因是它创建了一个列表,该列表具有容纳 1 个元素的容量,但仍然是空的。然而,new string[] { null } 创建了一个只有一个元素为 null 的字符串数组,这正是您想要的。

关于c# - 如何处理 foreach 中的 NullReferenceException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4487930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com