如何检查空数组

时间:2013-06-21 06:00:06

标签: arrays vb.net structure

我在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

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

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

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

现在,当我循环数组以检查空值时,它会抛出一个错误:

对象引用未设置为对象的实例。 (因为值包含“无”)

即使我这样检查,

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

如何检查数组的空元素?

3 个答案:

答案 0 :(得分:1)

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

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

new vertex

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

答案 1 :(得分: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

答案 2 :(得分: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