每个循环中没有任何集合 - 如何处理? [英] nothing collection in for each loop - how to handle it?

查看:26
本文介绍了每个循环中没有任何集合 - 如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当集合什么都没有时,我如何处理 for each 循环,我以为它会跳过但我得到了例外?

How do I handle a for each loop when the collection is nothing, I thought it would just skip over but i get an exeption?

我是否需要将 foreach 循环包装在 if 中以检查任何内容,并且仅当它不是任何内容时才进入 for each 循环?

Do I need to wrap the foreach loop in a if to check for nothing and only if it is not nothing then enter in the for each loop?

For Each item As String In MyStringList 

    'do something with each item but something myStringList will be nothing?


Next

推荐答案

我是否需要将 foreach 循环包装在 if 中以检查任何内容,并且仅当它不是任何内容时才进入 for each 循环?

Do I need to wrap the foreach loop in a if to check for nothing and only if it is not nothing then enter in the for each loop?

是的.

If MyStringList IsNot Nothing Then
    For Each item As String In MyStringList 
       'do something ...
    Next
End If

Microsoft 说这是有意为之:

我认为大多数 foreach 循环都是为了迭代一个非空集合.如果您尝试通过 null 进行迭代应该得到您的异常,以便您可以修复您的代码.Foreach是基本上是一种语法方便.因此,它不应该是神奇的"并在幕后做意想不到的事情.我同意那个帖子建议使用空集合而不是 null.(他们能通常使用单例技术重复使用很多).

I think that most foreach loops are written with the intent of iterating a non-null collection. If you try iterating through null you should get your exception, so that you can fix your code. Foreach is basically a syntactic convenience. As such, it should not be "magical" and do unexpected things under the hood. I agree with the post that proposed the use of empty collections rather than null. (They can typically be reused quite a bit using singleton techniques).

这篇关于每个循环中没有任何集合 - 如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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