0

我在 VB.net 工作,我的课程如下:

Public Class vertex
    Public wasVisited As Boolean
    Public name, type As String
    Public x_pos, y_pos As Double

    Public Sub New(ByVal x_pos As Double, ByVal y_pos As Double, ByVal name As Integer, ByVal type As String)
        Me.x_pos = x_pos
        Me.y_pos = y_pos
        Me.name = name
        Me.type = type
        wasVisited = False
    End Sub
End Class

我有一些名为“图”的其他类的对象,在图类的构造函数中,我正在调用顶点类的构造函数。

我有顶点类数组: Public vertices() As vertex

并且 redim vertices(2000): 出于某种原因再次调整数组大小。

现在,当我循环数组以检查空值时,它会引发错误:

你调用的对象是空的。(因为值包含“无”)

即使我这样检查,

If (vertices(i).name) Is Nothing Then
            Exit For
        End If

如何检查数组的空元素?

4

3 回答 3

1

vertices()redim 操作之前的大小是多少?如果它小于 2000,则添加的元素将Nothing在数组放大之后立即添加,因此当您尝试访问超出初始数组大小的 i 值的name属性时,您实际上是在尝试取消引用空对象引用。vertices(i)

您要么需要vertices(i) IsNot Nothing在测试其属性值之前检查这一点,要么确保为数组的每个元素分配一个new vertex对象。

If vertices(i) Is Nothing OrElse vertices(i).name Is Nothing Then
    Exit For
End If

这是关于类似问题的 vbforums 线程:http ://www.vbforums.com/showthread.php?546668-RESOLVED-Redim-array-of-objects

于 2013-06-21T06:21:17.900 回答
1

由于您似乎希望您的收藏是动态的,因此 List(Of vertex) 会更好地为您服务。它与默认的 New() 构造函数一起,您可以添加、删除、排序、搜索,无论您需要什么。要检查您可以使用的任何空值If Vertices(i).name = "" then

Public Class vertex
    Public wasVisited As Boolean
    Public name, type As String
    Public x_pos, y_pos As Double
    Public Sub New()
        wasVisited = False
        name = ""
        type = ""
        x_pos = 0
        y_pos = 0
    End Sub

    Public Sub New(ByVal x_pos As Double, ByVal y_pos As Double, ByVal name As String, ByVal type As String)
        Me.x_pos = x_pos
        Me.y_pos = y_pos
        Me.name = name
        Me.type = type
        wasVisited = False
    End Sub
End Class

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim Vertices As New List(Of vertex)
    For I = 0 To 99
        Vertices.Add(New vertex())
        Vertices(I).name = "Test" + I.ToString
    Next
End Sub
于 2013-06-21T07:19:05.887 回答
0

你有没有尝试过:

If Not vertices Is Nothing AndAlso Not vertices(i) Is Nothing _
            AndAlso Not vertices(i).name Is Nothing Then

   Dim value as string= vertices(i).name

End If
于 2013-06-21T06:13:30.580 回答