【问题标题】:For Each Loop in Visual Basic: IndexOutOfRangeException [closed]对于 Visual Basic 中的每个循环:IndexOutOfRangeException [关闭]
【发布时间】:2015-08-01 01:30:29
【问题描述】:

为什么下面的代码在VB.Net中会出现IndexOutOfRangeException:

    Dim intNum() As Integer = {1, 2, 3, 4, 5}
    Dim tot As Integer
    For Each n As Integer In intNum
        tot = tot + intNum(n)
    Next
    MsgBox(tot)

【问题讨论】:

  • 为什么不应该给出这样的例外?
  • 这和 Java 有什么关系?
  • 你确定这是 Java 吗?
  • 这是(很可能)VB。

标签: .net vb.net indexoutofrangeexception


【解决方案1】:

假设您的意思是VB.NET,数组索引的范围是从 0 到您在最后一个索引处超出的数组上限 4。如果你想总结你可以做的元素

For Each n As Integer In intNum
    tot = tot + n
Next

【讨论】:

    【解决方案2】:

    或者使用一些内置函数。

    Dim intNum() As Integer = {1, 2, 3, 4, 5}
    Dim total = intNum.Sum()
    

    【讨论】:

    • 你可能不会相信有多少人不使用扩展程序;很好的 ole' Linq 扩展来救援。
    • 我也是。我曾经遇到的唯一问题是当其他工程师之一因为令人困惑或阅读时间过长而被激怒时。但这也来自不使用它的人。它可以在您需要时发挥强大的作用......
    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 2015-03-15
    • 2015-12-06
    • 2018-07-16
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多