gpt4 book ai didi

c# - if(items != null) 在 foreach(T item in items) 之前是否多余?

转载 作者:IT王子 更新时间:2023-10-29 03:39:07 26 4
gpt4 key购买 nike

我经常遇到类似下面的代码:

if ( items != null)
{
foreach(T item in items)
{
//...
}
}

基本上,if 条件确保只有当 items 不为空时,foreach block 才会执行。我想知道是否真的需要 if 条件,或者 foreach 将处理 items == null 的情况。

我的意思是,我可以简单地写吗

foreach(T item in items)
{
//...
}

不用担心 items 是否为空? if 条件是否多余?或者这取决于 items类型,或者也可能取决于 T

最佳答案

你仍然需要检查 if (items != null) 否则你将得到 NullReferenceException。但是你可以这样做:

List<string> items = null;  
foreach (var item in items ?? new List<string>())
{
item.Dump();
}

但您可以检查它的性能。所以我还是更喜欢先有 if (items != null)。

根据 Eric 的 Lippert 建议,我将代码更改为:

List<string> items = null;  
foreach (var item in items ?? Enumerable.Empty<string>())
{
item.Dump();
}

关于c# - if(items != null) 在 foreach(T item in items) 之前是否多余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6455311/

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