[英]Using variables for referencing objects in vb.net (Visual Studio 2008)
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. 我有一个称为“ Tank”的公共类,在该类中,有一个整数类型的名为“ direction”的公共属性。
I keep getting the error: "Tank is a type and cannot be used as an expression" What I'm doing wrong here ? 我不断收到错误消息:“ 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
You don't have an array of Tanks: 您没有一系列的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: 如果您使用的是Visual Studio 2008,则可以使用:
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. 因此,您根本不需要For循环。
Well, Tank(i)
is not equivalent to Tank1
. 好吧, Tank(i)
不等于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 @ 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 ! 非常感谢你的帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.