0

当我在类级别声明变量并在过程中使用该变量时,有时会出现此错误“对象引用未设置为对象的实例”。

例如,这是我最近的一个项目,它创建了一个程序来显示特定温度下的物质状态:

 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,则程序可以完美运行。现在我知道是什么导致了错误,但我想知道为什么会出现这个问题。

4

2 回答 2

2

您不能使用控件的属性声明变量,因为该控件尚未初始化。您需要在输入一些文本之后而不是在有值之前设置值。

 Dim sngTemperature As Single = CSng(txtTemperature.Text)'no value here yet

只需将其声明为类级别:

 Dim sngTemperature As Single 

然后在按钮事件中设置它。

于 2013-10-17T02:52:57.010 回答
0
Dim sngTemperature As Single = CSng(txtTemperature.Text)

不要分配这样的变量。您假设 txtTemperature.Text 在 sngTempearature 之前初始化。轻松修复,更改为:

Dim sngTemperature As Single = 0

并改变你的方法开始:

Private Sub btnDisplayState_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayState.Click

  sngTemperature = CSng(txtTemperature.Text)

  If sngTemperature <= WATER_FP Then
     strSolid &= "Water "
  ' etc etc
于 2013-10-17T02:59:58.153 回答