是否可以使用String键/值对初始化新的System.Collections.Generic.Dictionary? [英] Is it possible to initialise a New System.Collections.Generic.Dictionary with String key/value pairs?
问题描述
是否可以创建和初始化 System.Collections.Generic.Dictionary
在一个语句中使用String键/值对的对象
Is it possible to create and initialise a System.Collections.Generic.Dictionary
object with String key/value pairs in one statement?
我是沿着一系列Strings的构造函数思考。
I'm thinking along the lines of the constructor for an array of Strings..
例如
Private mStringArray As String() = {"String1", "String2", "etc"}
如果事实证明是句法糖的事情,我会喜欢我可以在.Net 2.0(Visual Studio 2005)和Visual Basic中使用的答案 - 虽然我很好奇,如果这是可能的,所以不要让你失望; o)
In case this is turns out to be a syntactic sugar kind of thing, I'd prefer an answer that I can use in .Net 2.0 (Visual Studio 2005), and Visual Basic - though I'm curious if it's possible at all so don't let that put you off ;o)
推荐答案
我不认为有一种方法可以在VB.NET 2中开箱即用,但是您可以扩展通用字典按你想要的方式工作
I don't think there is a way to do this out of the box in VB.NET 2, however you can extend the generic dictionary to make it work the way you want it to.
下面的控制台应用如下所示:
The console app below illustrates this:
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim items As New FancyDictionary(Of Integer, String)(New Object(,) {{1, "First Item"}, {2, "Second Item"}, {3, "Last Item"}})
Dim enumerator As FancyDictionary(Of Integer, String).Enumerator = items.GetEnumerator
While enumerator.MoveNext
Console.WriteLine(String.Format("{0} : {1}", enumerator.Current.Key, enumerator.Current.Value))
End While
Console.Read()
End Sub
Public Class FancyDictionary(Of TKey, TValue)
Inherits Dictionary(Of TKey, TValue)
Public Sub New(ByVal InitialValues(,) As Object)
For i As Integer = 0 To InitialValues.GetLength(0) - 1
Me.Add(InitialValues(i, 0), InitialValues(i, 1))
Next
End Sub
End Class
End Module
这篇关于是否可以使用String键/值对初始化新的System.Collections.Generic.Dictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!