if(items != null) 在 foreach(T item in items) 之前是多余的吗? [英] Is if(items != null) superfluous before foreach(T item in items)?

查看:21
本文介绍了if(items != null) 在 foreach(T item in items) 之前是多余的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到如下代码:

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

基本上,if 条件确保 foreach 块仅在 items 不为空时才会执行.我想知道 if 条件是否真的需要,或者 foreach 会处理如果 items == 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)
{
    //...
}

不用担心items 是否为空?if 条件是多余的吗?或者这取决于itemstype,或者也取决于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?

推荐答案

你仍然需要检查 if (items != 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();
}

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

but you might check performance of it. So I still prefer having if (items != null) first.

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

Based on Eric's Lippert suggestion I changed code to:

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

这篇关于if(items != null) 在 foreach(T item in items) 之前是多余的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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