I'm having a problem when using variables in object names.
I have a Public class which is called "Tank" In that class, there is a public property called "direction" of an integer type.
I keep getting the error: "Tank is a type and cannot be used as an expression" What I'm doing wrong here ?
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
You don't have an array of 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
If you're using Visual Studio 2008 then you could use:
Private Tank1 As New Tank() With { .Direction = 1}
Private Tank2 As New Tank() With { .Direction = 1}
So you don't need the For loop at all.
Well, Tank(i)
is not equivalent to Tank1
. You would need to make a list of tanks, add your instances to it, and access them that way.
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
It needed a small correction and your example worked just fine ! Exactly what I needed !
Dim alltanks As List(Of Tank) = New List(Of Tank)
Thanks a lot for your help !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.