在类级别声明变量时,对象引用未设置为对象的实例

时间:2013-10-17 02:45:34

标签: .net vb.net winforms visual-studio-2010

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

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

 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,程序将完美运行。现在我知道导致错误的原因,而且我想知道为什么会出现这个问题。

2 个答案:

答案 0 :(得分:2)

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

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

只需声明它级别:

 Dim sngTemperature As Single 

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

答案 1 :(得分: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