2013-06-21 43 views
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 

我命名爲「圖」的一些其他類的對象,其中在圖類的構造函數我打電話頂點類的構造函數。

我頂點類的數組:公共頂點()作爲頂點

而REDIM頂點(2000):由於某種原因再次調整陣列。

現在,當i循環陣列來檢查空值它拋出一個錯誤:未設置爲一個對象的一個​​實例

對象引用。 (由於值包含「什麼」)

即使我檢查這樣

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

我怎麼能檢查數組的空元素?

回答

1

因爲你似乎想您的集合是動態的,一個列表(頂點),將更好地爲您服務。與默認的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 
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 
1

什麼的vertices()的REDIM操作之前的大小?如果它小於2000,那麼在數組放大後,添加的元素將爲Nothing,因此,當您嘗試訪問 的屬性時,對於超出初始數組大小的i值,您實際上試圖解引用null對象引用。

你要麼需要檢查vertices(i)IsNotNothing測試其物業的價值,或者確保陣列中的每個元素之前被分配一個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