繁体   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