为对象及其嵌套对象赋值

时间:2016-07-12 17:45:34

标签: vb.net

我是一个新手,我错过了一些简单的事情。我有两个课

Public Class Param
    Public Property temperature As String
    Public Property display As Boolean
    Public Property storage As Boolean
    Public Property reason As Boolean
    Public Property stats As Object
    Public Property errors As Object
End Class

Public Class getTemperature
    Public Property method As String
    Public Property params As Param()
    Public Property id As String
End Class

我想声明并为对象赋值,但我不断收到错误"对象引用未设置为对象的实例"在尝试为param中的项目赋值时。我不明白,我创建了对象GetTemperature和对象Params,我缺少什么?

 Dim GetTemp As New getTemperature    
    GetTemp.method = TextBoxMethod.Text
    GetTemp.id = TextBoxID.Text
    Dim params As New Param
    params.temperature = "true"
    'GetTemp.params(0) = params

我也尝试了,但得到了同样的答案:

 Dim GetTemp As New getTemperature    
    GetTemp.method = TextBoxMethod.Text
    GetTemp.id = TextBoxID.Text    
    GetTemp.params(0).temperature = "True"

2 个答案:

答案 0 :(得分:0)

试试这个:

Public Class Param
    Public Property temperature As String
    Public Property display As Boolean
    Public Property storage As Boolean
    Public Property reason As Boolean
    Public Property stats As Object
    Public Property errors As Object
End Class

Public Class getTemperature
    Public Property method As String
    Public Property params As List(Of Param)
    Public Property id As String

    Public Sub New()
        params = New List(Of Param)
    End Sub
End Class

所以你可以这样写:

        Dim a As New getTemperature
        a.params.Add(New Param)

答案 1 :(得分:0)

如果删除括号

,它将起作用
Public Class getTemperature
    Public Property method As String
    Public Property params As Param
    Public Property id As String
End Class

然后

Dim GetTemp As New getTemperature    
GetTemp.method = TextBoxMethod.Text
GetTemp.id = TextBoxID.Text
Dim params As New Param
params.temperature = "true"
GetTemp.params = params