在 VB.NET 中创建关联数组的正确方法是什么?
我是一个 PHP 人,在 PHP 中我会做如下的事情:
I'm a PHP guy, and in PHP I would do something like the following:
$variable = array('0001'=>'value1', '0010'=>'value2');
我对 VB.NET 还很陌生,那么如何将上述代码转换为 VB.NET?
I'm pretty new to VB.NET, so how do I translate the above code to VB.NET?
我想我必须使用字典:
Dim variable As New Dictionary(Of String, String)
variable.Add("0001", "value1")
variable.Add("0010", "value2")
这是正确的做法还是我应该为此使用其他方法?
Is this the correct way of doing it or should I use something else for this?
这是一种方式,或者如果您更喜欢单行初始化方式,您可以这样做:
It is a way, or if you prefer a one-liner way of initialization, you can do this:
Dim variable As New Dictionary(Of String, String) From { {"0001", "value1"}, {"0010", "value2"} }
至于哪个更好,更多的是编码标准和/或个人偏好的问题.
As far as which is the better one, it's more a matter of coding standard, and/or personal preference.
考虑使用哪种容器,您应该只使用来自 System.Collection 的容器.NET 中的 .Generics 除非您另有要求.而 Dictionary 是默认的关联容器.您可以查看替代方案(例如 SortedDictionary),如果它更符合您的用例.
Considering what kind of container to use, you should use only those from System.Collection.Generics in .NET unless you are forced otherwise. And Dictionary is the default associative container. You can see the alternatives (SortedDictionary for example), if it matches more your use case.