VB.NET中循环遍历空集合应如何操作?

2026-05-08 11:573阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计305个文字,预计阅读时间需要2分钟。

VB.NET中循环遍历空集合应如何操作?

当集合中什么都没有时,我如何处理每个循环,我认为它可能会跳过,但我得到一个例外?我是否需要将foreach循环包含在if语句中以检查什么,只有当它不是什么都没有时,然后输入for each循环?

当集合什么都没有时我如何处理每个循环,我认为它会跳过但我得到一个例外?

我是否需要将foreach循环包装在if中以检查什么,只有当它不是什么都没有时,然后输入for each循环?

For Each item As String In MyStringList 'do something with each item but something myStringList will be nothing? Next

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?

是.

VB.NET中循环遍历空集合应如何操作?

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

Microsoft说这是设计:

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).

本文共计305个文字,预计阅读时间需要2分钟。

VB.NET中循环遍历空集合应如何操作?

当集合中什么都没有时,我如何处理每个循环,我认为它可能会跳过,但我得到一个例外?我是否需要将foreach循环包含在if语句中以检查什么,只有当它不是什么都没有时,然后输入for each循环?

当集合什么都没有时我如何处理每个循环,我认为它会跳过但我得到一个例外?

我是否需要将foreach循环包装在if中以检查什么,只有当它不是什么都没有时,然后输入for each循环?

For Each item As String In MyStringList 'do something with each item but something myStringList will be nothing? Next

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?

是.

VB.NET中循环遍历空集合应如何操作?

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

Microsoft说这是设计:

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).