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

如何在VB.NET中创建对象数组?遇System.NullReferenceException求助

解决你的VB.NET NullReferenceException问题

首先,咱们直奔核心——你遇到的System.NullReferenceException完全是因为数组里的对象没有被正确初始化。先看你的Main方法代码:

Dim ThisGame(6) As Toy
ThisGame(6) = New Toy
ThisGame(1).SetID("23456a") ' 这里直接报错,因为ThisGame(1)还是Nothing!

当你声明Dim ThisGame(6) As Toy时,VB.NET会创建一个包含7个元素的数组(索引从0到6),但所有元素默认都是Nothing(也就是C#里的null)。你只初始化了索引6的元素,其他位置的ThisGame(1)、ThisGame(2)都没有实例化,调用它们的方法自然会触发空引用异常。


第一步:修复数组初始化问题

你需要为每个要使用的数组元素创建Toy(或其子类)的实例,比如:

Sub Main()
    Dim ThisGame(6) As Toy
    ' 初始化需要用到的数组元素
    ThisGame(1) = New Toy()
    ThisGame(2) = New Toy()
    ThisGame(6) = New Toy()

    ThisGame(1).SetID("23456a")
    ThisGame(2).SetID("236789b")
    Console.WriteLine(ThisGame(1).GetID)
    Console.ReadKey()
End Sub

第二步:修复代码里的其他致命问题

除了空引用,你的代码还有几个会导致程序卡死或逻辑错误的问题,一起帮你梳理:

  1. Toy类GetName方法的数组错误
Public Function GetName()
    Return Name(Count) ' Name是单个String变量,不是数组!这里会抛索引越界异常
End Function

直接返回Name即可,同时建议给函数指定返回类型(VB.NET最佳实践):

Public Function GetName() As String
    Return Name
End Function
  1. 死循环的验证逻辑
    比如SetID方法里的循环,没有更新输入值会永远卡着:
Public Sub SetID(ByVal I As String)
    While Len(I) < 4
        Console.WriteLine("Kindly Enter the ID with Length of at least 4 Characters")
        I = Console.ReadLine() ' 让用户重新输入新的ID
    End While
    ID = I
End Sub
  1. 逻辑错误的循环条件
    比如SetConsole方法,Or的条件永远为真(一个字符串不可能同时等于PS4和XBOX),要换成AndAlso:
Public Sub SetConsole(ByVal C As String)
    While C <> "PS4" AndAlso C <> "XBOX"
        Console.WriteLine("Invalid console entered. Please enter PS4 or XBOX")
        C = Console.ReadLine() ' 允许用户修正输入
    End While
    Consol = C
End Sub

SetType方法的循环条件也犯了同样的错误,改成:

While TY <> "Car" AndAlso TY <> "Bus" AndAlso TY <> "Truck"
    Console.WriteLine("Vehicle is not in list! Please enter Car, Bus, or Truck")
    TY = Console.ReadLine()
End While
  1. SetUserAge的逻辑漏洞
    注释说"Minimum age is 18",但原条件冗余且没有允许用户重新输入:
Public Sub SetUserAge(ByVal SM As Integer)
    While SM < 18
        Console.WriteLine("Minimum age is 18. Please enter a valid age:")
        Integer.TryParse(Console.ReadLine(), SM) ' 解析用户输入的新年龄
    End While
    MinimumAge = SM
End Sub

总结

先解决数组初始化的问题,就能立刻消除NullReferenceException,再逐一修复其他逻辑错误和死循环,你的程序就能正常运行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:07:38