And*_*rew 22 vb.net dictionary initialization .net-2.0
是否可以System.Collections.Generic.Dictionary
在一个语句中使用String键/值对创建和初始化对象?
我正在思考一个字符串数组的构造函数.
例如
Private mStringArray As String() = {"String1", "String2", "etc"}
Run Code Online (Sandbox Code Playgroud)
如果这是一个语法糖类的东西,我更喜欢我可以在.Net 2.0(Visual Studio 2005)和Visual Basic中使用的答案 - 虽然我很好奇它是否可能如此不要让那让你失望; o)
jga*_*fin 77
像这样:
Dim myDic As New Dictionary(Of String, String) From {{"1", "One"}, {"2", "Two"}}
Run Code Online (Sandbox Code Playgroud)
我不认为有一种方法可以在VB.NET 2中开箱即用,但是你可以扩展通用字典,使其按照你想要的方式工作.
下面的控制台应用说明了这一点
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
Run Code Online (Sandbox Code Playgroud)
小智 5
试试这个语法:
Dictionary<string, double> dict = new Dictionary<string, double>()
{
{ "pi", 3.14},
{ "e", 2.71 }
};
Run Code Online (Sandbox Code Playgroud)
但这可能需要C#3(.NET 3.5)
归档时间: |
|
查看次数: |
14001 次 |
最近记录: |