填充数组数组时“对象引用未设置为对象的实例”

时间:2015-07-02 16:02:30

标签: arrays vb.net visual-studio-2010 object

您好我有以下代码

Partial Public Class DT_AnalyseDetail

    Private componentField As String
    Private contentField As String

    Public Property Component() As String
    Get
        Return Me.componentField
    End Get
    Set(value As String)
        Me.componentField = Value
    End Set
    End Property

    Public Property Content() As String
    Get
         Return Me.contentField
    End Get
    Set(value As String)
        Me.contentField = Value
    End Set
    End Property
End Class

Partial Public Class DT_Analyse

    Private detailField() As DT_AnalyseDetail
    Private batchField As String

    Public Property Detail() As DT_AnalyseDetail()
    Get
        Return Me.detailField
    End Get
    Set(value As DT_AnalyseDetail())
        Me.detailField = value
    End Set
    End Property

    Public Property Batch() As String
    Get
        Return Me.batchField
    End Get
    Set(value As String)
        Me.batchNoField = Value
    End Set
    End Property
End Class

Sub()

    Dim a_Myana(1) As DT_Analyse
    Dim a_Mydet(1) As DT_AnalyseDetail

    a_Mydet(0) = New DT_AnalyseDetail
    a_Mydet(0).Component = "TEST"
    a_Mydet(0).Content= "YES"

    a_Myana(0) = New DT_Analyse
    a_Myana(0).Batch= "123"
    a_Myana(0).Detail(0) = New DT_AnalyseDetail
    a_Myana(0).Detail(0) = a_Mydet(0)

End Sub

当我想填充a_Myana(0)时发生错误.Detail(0)= a_Mydet(0) 我猜我的Class / array定义不正确。但我不知道如何处理它。 “细节”是否需要更多尺寸? 类定义是由xesd文件中的visual studio xsd.exe编写的。

2 个答案:

答案 0 :(得分:2)

这一行不能完成你认为的所有事情:

Dim a_Mydet(1) As DT_AnalyseDetail

您认为它会创建一组DT_AnalyseDetail个对象,但这会发生。相反,它会创建一个DT_AnalyseDetail对象引用的数组。此时,每个引用的值都为Nothing(引用不引用任何对象)。这些Nothing引用尚未为Component属性分配空间,因此分配的行失败。

顺便说一下,这里有两个引用,而不是一个,因为默认情况下VB.Net数组是0索引的。

要修复代码,您需要执行以下操作:

Sub()

    Dim a_Mydet(1) As DT_AnalyseDetail
    a_Mydet(1) = New DT_AnalyseDetail()
    a_Mydet(1).Component = "TEST"

End Sub

现在查看更新后的问题。

你有以下几行:

a_Myana(0) = New DT_Analyse
a_Myana(0).Batch= "123"
a_Myana(0).Detail(0) = New DT_AnalyseDetail
a_Myana(0).Detail(0) = a_Mydet(0)

在这里,您期望New DT_Analyse表达式为Detail属性创建一个新数组。这会发生。数组是对象。属性是对象引用。与上一期一样,您必须首先确保对象引用引用Nothing以外的内容。你需要这样做:

a_Myana(0) = New DT_Analyse
a_Myana(0).Batch= "123"
 a_Myana(0).Detail = New DT_AnDT_AnalyseDetail(0)
a_Myana(0).Detail(0) = New DT_AnalyseDetail
a_Myana(0).Detail(0) = a_Mydet(0)

答案 1 :(得分:0)

而不是

a_Myana(0).Detail(0) = New DT_AnalyseDetail
a_Myana(0).Detail(0) = a_Mydet(0)

我设置

a_Myana(0).Detail() = a_Mydet

它有效:)