You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中如何避免循环迭代时数组被覆盖?

问题分析

你当前代码里的EmployeeData = Line.Split(" ")是直接把每行分割出的新数组赋值给EmployeeData变量,这会完全覆盖数组之前的内容,而非追加新元素,这就是核心问题。

解决方案

要实现追加效果,你需要把每行分割得到的元素逐个复制到EmployeeData数组的对应位置,而非直接替换整个数组。同时可以优化分割逻辑,避免空字符串干扰:

Do Until StreamReader.Peek() = -1 _
        OrElse intSubscript >= EmployeeData.Length
    Dim Line As String = StreamReader.ReadLine()
    ' 分割行内容,移除空字符串(避免行首尾或连续空格产生无效空元素)
    Dim splitElements As String() = Line.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
    
    ' 遍历分割后的元素,逐个追加到EmployeeData数组中
    For Each element As String In splitElements
        ' 提前检查数组容量,防止索引越界
        If intSubscript >= EmployeeData.Length Then
            Exit For
        End If
        EmployeeData(intSubscript) = element
        intSubscript += 1
    Next
Loop
关键说明
  • 用StringSplitOptions.RemoveEmptyEntries过滤分割时产生的空字符串,确保只有有效数据存入数组
  • 通过循环逐个将分割元素放入EmployeeData的对应索引位置,而非直接替换整个数组
  • 每次添加元素前检查数组容量,避免出现索引越界错误

内容的提问来源于stack exchange,提问作者CousinMoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:05:37