在VB中声明并定义Property

时间:2014-10-15 12:22:52

标签: vb.net

我有两个Class,我想将数据保存到数组文本框中,如下所示:
Students.Name(txtID.Text-1).MathMark = txtMark.Text
但我收到错误:对象引用未设置为对象的实例

我的代码是:

Dim StudentsNumber as Integer = txtstdnum.Text
Dim Students as New StudentsInf(StudentsNumber)

Students.Name(txtID.Text-1).MathMark = txtMark.Text


Public Class StudentsInf

    Private mName() As String

    Sub New(ByVal StudentNumbers As Integer)
        ReDim mName(StudentNumbers-1)
    End Sub

    Public Property Name(ByVal Index As Integer) As LessonsMark
        Get
            Return mName(Index)
        End Get
        Set(ByVal Value As LessonsMark)
            mName(Index) = Value
        End Set
    End Property

End Class

Public Class LessonsMark

    Private mMathMark() As Object

    Public Property MathMark() As Object
        Get
            Return mMathMark
        End Get
        Set(ByVal Value As Object)
            mMathMark = Value
        End Set
    End Property

End Class

1 个答案:

答案 0 :(得分:1)

此:

Private mName() As String

需要:

Private mName() As LessonsMark

然后你必须在构造函数中创建对象,如:

Sub New(ByVal StudentNumbers As Integer)
  ReDim mName(StudentNumbers - 1)
  For i As Integer = 0 To StudentNumbers - 1
    mName(i) = New LessonsMark()
  Next
End Sub

然后看起来你的LessonsMark类声明它应该只是一个字符串属性时声明一​​个对象数组:

Public Class LessonsMark
  Private mMathMark As String

  Public Property MathMark As String
    Get
      Return mMathMark
    End Get
    Set(ByVal Value As String)
      mMathMark = Value
    End Set
  End Property
End Class