当我在类级别声明变量并在过程中使用该变量时,有时会出现此错误“对象引用未设置为对象的实例”。
例如,这是我最近的一个项目,它创建了一个程序来显示特定温度下的物质状态:
Public Class Form1
Const WATER_FP As Integer = 0
Const WATER_BP As Integer = 100
Const ETHANOL_FP As Integer = -114
Const ETHANOL_BP As Integer = 78
Const MERCURY_FP As Integer = -39
Const MERCURY_BP As Integer = 357
Const OXYGEN_FP As Integer = -219
Const OXYGEN_BP As Integer = -183
Dim strSolid As String = vbNullString
Dim strGas As String = vbNullString
Dim sngTemperature As Single = CSng(txtTemperature.Text)
Private Sub btnDisplayState_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayState.Click
If sngTemperature <= WATER_FP Then
strSolid &= "Water "
ElseIf sngTemperature >= WATER_BP Then
strGas &= "Water "
End If
If sngTemperature <= ETHANOL_FP Then
strSolid &= "Ethanol "
ElseIf sngTemperature >= ETHANOL_BP Then
strGas &= "Ethanol "
End If
If sngTemperature <= MERCURY_FP Then
strSolid &= "Mercury "
ElseIf sngTemperature >= MERCURY_BP Then
strGas &= "Mercury "
End If
If sngTemperature <= OXYGEN_FP Then
strSolid &= "Oxygen "
ElseIf sngTemperature >= OXYGEN_BP Then
strGas &= "Oxygen "
End If
If strSolid <> vbNullString Then
strSolid = "Substances that are in solid state are " & strSolid
Else
strSolid = "No substances are in solid state."
End If
If strGas <> vbNullString Then
strGas = "Substances that are in gaseous state are " & strGas
Else
strGas = "No substances are in gaseous state."
End If
lblMessage.Text = strSolid & ControlChars.CrLf & strGas
End Sub
End Class
调试时,我收到如上所述的错误,没有突出显示代码导致问题的位置。但是,如果我将变量移入btnDisplayState_Click
,则程序可以完美运行。现在我知道是什么导致了错误,但我想知道为什么会出现这个问题。