【问题标题】:Null Reference Exception when writing to custom class写入自定义类时出现空引用异常
【发布时间】:2016-06-01 03:25:34
【问题描述】:

所以我刚开始在 VB 中使用自定义类,并在尝试编写时遇到此错误。我试着按照老师的例子,但也想深入了解 VB 的一些更高级的方面,并尝试在我的课程中使用数组,结果不太好。

Form1 类:

Dim mypt(7) As Point

Private Sub Create_Click(sender As Object, e As EventArgs) Handles Create.Click
    PtSelect = Input()  'Returns an int
    mypt(PtSelect).mC(0) = CDec(IX.Text) 'Error here!
    mypt(PtSelect).mC(1) = CDec(IY.Text)
    mypt(PtSelect).mC(2) = CDec(IZ.Text)
End Sub

点类:

Public Class Point
Private c(2) As Decimal

Public Sub New(ByVal X As Decimal, ByVal Y As Decimal, ByVal Z As Decimal)
    c(0) = X
    c(1) = Y
    c(2) = Z
End Sub

Public Property mC(Val As Integer) As Decimal
    Get
        Return c(Val)
    End Get
    Set(value As Decimal)
        c(Val) = value
    End Set
End Property
End Class

真的只是不确定在这一点之后该怎么做,我已经摆弄了所有我能想到的东西,但我不确定。我的老师确实说过在我遇到错误之前可以在课堂上使用数组,我想让它工作。

【问题讨论】:

    标签: arrays vba class


    【解决方案1】:

    在Vb.net中使用类时,它使用了指针的概念。这意味着每个变量都指向一个对象。所以当你实例化你的数组时

     Dim mypt(7) As Point
    

    它创建了一个包含 8 个指针的数组,每个指针都包含值 Nothing。你必须用

    调用你的类Point的构造函数
    New Point(2,2,3)
    

    并使数组中的指针指向该对象。

    mypt(1) = New Point(2,2,3)
    

    【讨论】:

    • 就是这样!感谢您的帮助!
    【解决方案2】:

    (代表 OP 发布)。

    感谢用户 Matriac!我唯一需要做的改变是:

        mypt(PtSelect).mC(0) = CDec(IX.Text) 'Error here!
        mypt(PtSelect).mC(1) = CDec(IY.Text)
        mypt(PtSelect).mC(2) = CDec(IZ.Text)
    

    到这里:

    mypt(PtSelect) = New Point(CDec(IX.Text), CInt(IY.Text), CDec(IZ.Text))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 2017-10-04
      相关资源
      最近更新 更多