繁体   English   中英

在python中,我执行“ dictionary = {“ key”:[value,value],(etc)}”。如何在Visual Basic中做到这一点?

[英]In python I do “dictionary = {”key“: [value, value], (etc)}” How do I do this in Visual Basic?

我正在VB中为我的计算机科学课做一个小型冒险游戏,并且要对角色进行盘点,我需要知道如何制作字典(这样我才能得到商品的名称)和清单作为值项目(列表类似于obj = [Quantity,Damage_Dealt(或Health_Received)])。 我做了一些研究,我试图做

Dim knife As New List(Of Integer)
knife.add(1)#the first one is how many knives and the second is the dmg
knife.add(1)

Dim inv As New Dictionary(Of String, List(Of Integer))
inv.add("knife", knife)

但是有些东西丢失了,或者希望有一种更简单的方法可以做到。 即使可以创建2或3维数组(例如inv = [[knife, 1, 1], [bread, 2, 0]]

我将很欣赏更改python的最直接方法

dictionary = {"key": [value, value], (etc)}

进入VB提前谢谢

我忘了提到所有在类中的子类中。

您完全可以制作一个新列表(字典(字符串,列表(整数)))并填充它。

您似乎已经知道代码了。 祝您实施愉快!

这是一个如何完成您要寻找的东西的基本示例。

Public Sub TestData()
        //Create List and populate it

        Dim list As New List(Of KeyValuePair(Of String, List(Of Integer)))
        Dim integerList As List(Of Integer) = New List(Of Integer)
        integerList.Add(1)
        integerList.Add(2)

        list.Add(New KeyValuePair(Of String, List(Of Integer))("Test", integerList))



        //Iterate through the list to get data

        For Each pair As KeyValuePair(Of String, List(Of Integer)) In list
            Dim key As String = pair.Key

            Dim newIntegerList As New List(Of Integer)
            For Each value As Integer In pair.Value
                newIntegerList.Add(value)
            Next
        Next
    End Sub

编辑:不得不将注释更改为C#注释,因为它不喜欢VB注释。 但是显然您会摆脱这些。

有多种方法可以通过创建列表字典或数组字典来实现。 但是,如果必须依靠索引来查找正确的属性,则代码将变得混乱。

更好的选择是使用元组 但是,这些被更多地认为是用于临时存储,用于中间结果以及用于返回多个值的函数。

项目是游戏的重要方面。 创建一个Item类! 这将使您更轻松地处理物品

Public Class Item
    Property Quantity As Integer
    Property Damage As Integer
    Property Health As Integer
End Class

您可以使用

Dim Items As New Dictionary(Of String, Item) From {
   {"knife", New Item With {.Quantity = 1, .Damage = 0, .Health = 100}},
   {"arrow", New Item With {.Quantity = 5, .Damage = 0, .Health = 100}}
}

现在,您可以轻松检索属性

Dim knifeDamage = Items("knife").Damage

还具有其他优点:您可以向其添加Subs和Function,可以派生具有仅适用于它们的属性的更多特定项目类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM