在 foreach 循环中检查 null [英] Check for null in foreach loop

查看:47
本文介绍了在 foreach 循环中检查 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法来执行以下操作:
在继续循环之前,我需要检查 file.Headers 上是否发生 null

Is there a nicer way of doing the following:
I need a check for null to happen on file.Headers before proceeding with the loop

if (file.Headers != null)
{
  foreach (var h in file.Headers)
  {
   //set lots of properties & some other stuff
  }
}

简而言之,由于我的代码中发生的缩进级别,在 if 中编写 foreach 看起来有点难看.

In short it looks a bit ugly to write the foreach inside the if due to the level of indentation happening in my code.

是评估为

foreach(var h in (file.Headers != null))
{
  //do stuff
}

可能吗?

推荐答案

就像对 Rune 的建议稍加修饰一样,您可以创建自己的扩展方法:

Just as a slight cosmetic addition to Rune's suggestion, you could create your own extension method:

public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

然后你可以写:

foreach (var header in file.Headers.OrEmptyIfNull())
{
}

根据口味更改名称:)

这篇关于在 foreach 循环中检查 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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