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

为何出现‘Object reference not set to an instance of the object’异常?附报错代码

解决“Object reference not set to an instance of the object”异常

嘿,这个空引用异常是VB.NET里超常见的问题,咱们一步步揪出你代码里的问题:

问题根源分析

你的代码里有两个关键问题会触发这个异常:

  • customersFile未被初始化:你调用了File.OpenText("F:\CustomerRecords.txt"),但没有把返回的StreamReader对象赋值给customersFile变量,导致customersFile是Nothing(VB.NET里的空引用)。当你尝试调用customersFile.ReadLine()时,自然就会抛出空引用异常。
  • 未处理ReadLine()返回Nothing的情况:就算你正确初始化了customersFile,当文件读到末尾时,ReadLine()会返回Nothing,这时候再调用.ToString()也会触发同样的异常。

修正后的代码

这里给你调整后的代码,同时加入了资源安全处理和空值检查:

Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
    ' 使用Using语句自动释放StreamReader资源,避免内存泄漏
    Using customersFile As IO.StreamReader = IO.File.OpenText("F:\CustomerRecords.txt")
        Dim customer As New CustomerRecord
        ' 先读取一行并检查是否为空
        Dim line As String = customersFile.ReadLine()
        If line IsNot Nothing Then
            customer.strLastName = line
            lblLastName.Text = customer.strLastName
        Else
            ' 文件已经读完,这里可以加个提示
            lblLastName.Text = "没有更多记录了"
        End If
    End Using
End Sub

额外提示

  • 永远记得检查可能返回空值的对象或方法返回值,尤其是IO操作相关的——文件可能不存在、为空或者权限不足(权限问题会是另一种异常,但提前处理总是好的)。
  • 使用Using语句处理实现了IDisposable的对象(比如StreamReader),能确保资源被正确释放,避免潜在的内存问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:53:55