簡體   English   中英

使用變量引用vb.net中的對象(Visual Studio 2008)

[英]Using variables for referencing objects in vb.net (Visual Studio 2008)

在對象名稱中使用變量時遇到問題。

我有一個稱為“ Tank”的公共類,在該類中,有一個整數類型的名為“ direction”的公共屬性。

我不斷收到錯誤消息:“ Tank是一種類型,不能用作表達式”我在這里做錯了什么?

Public Class mainroutines()

' Create Instances of tank  

Private Tank1 As New Tank()
Private Tank2 As New Tank()

'Loop trough objects and set the property value

dim i as integer
For i = 1 to 2
Tank(i).direction = 1
next i

End class

您沒有一系列的Tanks:

Public Class mainroutines()

' Create Instances of tank  

Private Tank1 As New Tank()
Private Tank2 As New Tank()

'Loop trough objects and set the property value
Dim tanks() As Tank

tanks(0) = Tank1
tanks(1) = Tank2

For i As Integer = 1 To 2
   tanks(i).direction = 1
next

End class

如果您使用的是Visual Studio 2008,則可以使用:

Private Tank1 As New Tank() With { .Direction = 1}
Private Tank2 As New Tank() With { .Direction = 1}

因此,您根本不需要For循環。

好吧, Tank(i)不等於Tank1 您需要制作一個坦克清單,向其中添加實例,然后以這種方式訪問​​它們。

Public Class mainroutines() 

' Create Instances of tank '  

Dim allTanks As List(Of Tank) = New List(Of Tank) 
allTanks.Add(New Tank())
allTanks.Add(New Tank())

'Loop through objects and set the property value '

dim i as integer 
For i = 1 to 2 
allTanks(i).direction = 1 
next i 

@ Jball

需要進行一些小的更正,您的示例效果很好! 正是我需要的!

Dim alltanks As List(Of Tank) = New List(Of Tank)

非常感謝你的幫助 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM