null检查作为for / foreach循环的一部分 [英] null checking as part of for/foreach loop

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

问题描述

有没有办法在foreach循环中检查null? 因此,而不是

    if      images  !=     null    
{
foreach var link in images


这将是

    foreach      var   link   in   images?  

如果图像为空则循环不会执行?  


并扩展,而不是

   如果   (list!= null&& list。  images  !=     null    
{
foreach var link in list.images

类似

    foreach      var   link   in   list?.images?  

解决方案

< blockquote>

有没有办法在foreach循环中检查null?  



没有办法按照你想要的方式去做。


有很多方法可以使用匿名方法来做,但是很麻烦,可维护性差,性能差。


我们可以知道您不希望将foreach放在if块中的原因吗?


Is there a way to check for null in a foreach loop?  So instead of

                if (images != null)
                {
                    foreach (var link in images)

It would be

                    foreach (var link in images?)

and if images was null the loop would not execute?  

and expanding on that, instead of

                if (list != null && list.images != null)
                {
                    foreach (var link in list.images)

something like

 foreach (var link in list?.images?)

解决方案

Is there a way to check for null in a foreach loop?  

No there is not a way to do it the way you want.

There are ways of using anonymous methods to do it but would be cumbersome, have poor maintainability and poor performance.

May we know the reason why you don't want to place the foreach inside the if block?


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

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