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

VB.NET子程序中给一维数组赋值抛出NullReferenceException如何解决

异常触发原因

数组属于引用类型,你仅声明了inputChordsUser为字符串数组类型的属性,但没有对其进行初始化,其默认值就是Nothing。不管是读取数组元素还是给数组元素赋值,运行时都需要先定位到数组实例的内存地址,才能操作对应索引位置的存储区域。数组实例本身不存在的情况下,任何索引访问操作都会触发NullReferenceException,和操作是读还是写无关。
你之前尝试将inputChordsUser作为参数传入仍未解决,本质是因为你传入的还是未初始化的空引用,没有解决实例不存在的核心问题。

可行修复方案
  • 方案1:提前知晓数组固定长度的场景,在类构造函数中初始化数组
    比如你确定最多存储100个和弦数据,在类的构造方法中添加初始化逻辑:
    Public Sub New()
        ' 数组长度为100,索引范围0-99
        inputChordsUser = New String(99) {}
    End Sub
    
    注意要确保后续使用的CounterPublic不会超出数组的索引范围,否则会触发索引越界异常。
  • 方案2:长度不固定的场景,推荐用List(Of String)替代数组
    List(Of T)是动态扩容的集合类型,无需提前指定长度,使用更灵活:
    1. 修改属性定义:
    ' 直接初始化集合实例
    Public Property inputChordsUser As New List(Of String)
    
    1. 修改SendChords中的赋值逻辑:
    Public Sub SendChords(ByRef Final As String, ByRef CounterPublic As Integer)
        ' 直接添加元素,无需手动维护索引
        inputChordsUser.Add(Final)
        ' 如果确实需要按CounterPublic指定位置赋值,可先判断扩容
        ' If inputChordsUser.Count <= CounterPublic Then
        '     inputChordsUser.AddRange(New String(CounterPublic - inputChordsUser.Count + 1) {})
        ' End If
        ' inputChordsUser(CounterPublic) = Final
    End Sub
    
  • 方案3:必须使用动态长度数组的场景,赋值前先扩容数组
    使用ReDim Preserve语句调整数组大小,保留原有数据:
    Public Sub SendChords(ByRef Final As String, ByRef CounterPublic As Integer)
        ' 先确保数组长度足够容纳当前索引
        If inputChordsUser Is Nothing Then
            ReDim inputChordsUser(CounterPublic)
        ElseIf inputChordsUser.Length <= CounterPublic
            ReDim Preserve inputChordsUser(CounterPublic)
        End If
        inputChordsUser(CounterPublic) = Final
    End Sub
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:54:00