vb.net 如何创建对象数组 Visual Basic

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16724938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:55:37  来源:igfitidea点击:

How to create an array of objects Visual Basic

arraysvb.netobject

提问by Dany

Is it possible to create an array of objects in visual basic?

是否可以在visual basic中创建一组对象?

I'm making a battle system and whenever the battle begins, i wanna be able to randomly select a Monster object from an array.

我正在制作一个战斗系统,每当战斗开始时,我希望能够从数组中随机选择一个 Monster 对象。

If it is possible, could somebody show me how to store Public Spider as New Monster(50, 20, 5)into an array?

如果可能,有人可以告诉我如何存储Public Spider as New Monster(50, 20, 5)到数组中吗?

Thank you.

谢谢你。

Monster Class:

怪物等级:

Public Class Monster

  Private hp As Integer
  Private xp As Integer
  Private dmg As Integer

  Sub New(ByVal hitpoints As Integer, ByVal exp As Integer, ByVal damage As Integer)
    hp = hitpoints
    xp = exp
    dmg = damage
  End Sub

End Class

Form Class:

表格类:

Imports Monster
Public Class Form

  Public Spider As New Monster(50, 20, 5)

End Class

回答by OneFineDay

A List(Of T)would work great for that.

一个List(Of T)可以很好地解决这个问题。

Private Monsters As New List(Of Monster)
'later add them into this collection
Monsters.Add(New Monster(50, 20, 5))

回答by Adrian

You could use one of the Collectionslike List(of Monster)to hold it if you don't have a set and knowable number of class instances to store.

你可以使用一个Collections喜欢List(of Monster)拿着它,如果你没有一套和类实例存储的可知数。

Dim Monsters As List(of Monster) = New List(of Monster)
Monsters.Add(New Monster(10, 50, 30))