有没有办法可以在创建 VB.NET 字典时将值插入其中?我可以,但不想,为每个项目执行 dict.Add(int, "string") 。
基本上,我想做 "How to insert values into C# Dictionary on instantiation?"与VB.NET。
var dictionary = new Dictionary<int, string>
{
{0, "string"},
{1, "string2"},
{2, "string3"}
};
最佳答案
如果使用 Visual Studio 2010 或更高版本,您应该使用 FROM
关键字,如下所示:
Dim days = New Dictionary(Of Integer, String) From {{0, "string"}, {1, "string2"}}
参见:http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx
如果您需要使用 Visual Studio 的早期版本并且需要经常执行此操作,您可以继承 Dictionary 类并自行实现。
它可能看起来像这样:
Public Class InitializableDictionary
Inherits Dictionary(Of Int32, String)
Public Sub New(ByVal args() As KeyValuePair(Of Int32, String))
MyBase.New()
For Each kvp As KeyValuePair(Of Int32, String) In args
Me.Add(kvp.Key, kvp.Value)
Next
End Sub
End Class
关于vb.net - 如何在实例化时将值插入到 VB.NET 字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664514/