是,如果(项目!= NULL)多余的foreach之前(T中的项项)? [英] Is if(items != null) superfluous before foreach(T item in items)?
问题描述
我经常遇到类似于下面的代码:
I often come across code like the following:
if ( items != null)
{
foreach(T item in items)
{
//...
}
}
基本上,如果
条件保证了的foreach
块将只执行如果项目
不为空。我不知道是否是真正需要的如果
的条件,或的foreach
将处理的情况下,如果项目== NULL
。
Basically, the if
condition ensures that foreach
block will execute only if items
is not null. I'm wondering if the if
condition is really needed, or foreach
will handle the case if items == null
.
我的意思是,我可以简单的写
I mean, can I simply write
foreach(T item in items)
{
//...
}
无需担心是否项目
为空或不是?是如果
条件多余的?或者这要看的键入的的项目
或者在 T
以及
without worrying about whether items
is null or not? Is the if
condition superfluous? Or this depends on the type of items
or maybe on T
as well?
推荐答案
您还需要检查(项目!= NULL),否则你将得到的NullReferenceException。但是你可以做这样的事情:
You still need to check if (items != null) otherwise you will get NullReferenceException. However you can do something like this:
List<string> items = null;
foreach (var item in items ?? new List<string>())
{
item.Dump();
}
但你可能要检查它的性能。 (!项目= NULL)。所以,我还是比较喜欢有,如果第一个
but you might check performance of it. So I still prefer having if (items != null) first.
根据Eric的利珀特建议我改变代码:
Based on Eric's Lippert suggestion I changed code to:
List<string> items = null;
foreach (var item in items ?? Enumerable.Empty<string>())
{
item.Dump();
}
这篇关于是,如果(项目!= NULL)多余的foreach之前(T中的项项)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!