为您在foreach循环空 [英] Check for null in foreach loop
本文介绍了为您在foreach循环空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有这样做以下的更好的方式:结果
我需要为空的检查与循环继续之前对file.Headers发生
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
}
}
在短期看起来有点丑写在里面在foreach如果由于压痕的水平在我的code发生。
In short it looks a bit ugly to write the foreach inside the if due to the level of indentation happening in my code.
时的东西,将计算结果为
Is something that would evaluate to
foreach(var h in (file.Headers != null))
{
//do stuff
}
可能吗?
推荐答案
就像轻微化妆品除了符文的建议,你可以创建自己的扩展方法:
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>();
}
然后,你可以写:
Then you can write:
foreach (var header in file.Headers.OrEmptyIfNull())
{
}
根据口味改变名称:)
Change the name according to taste :)
这篇关于为您在foreach循环空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文