Convert this C# dictionary to VB.NET
How do I convert the following C# code to VB.NET?
The conversion tool is not doing a good job.
private static readonly Dictionary<string, List<string>> ValidHtmlTags = new Dictionary<string, List<string>> {
{ "param", new List<string>() {"name","value"}},
{ "object", new List<string>开发者_如何学JAVA;() {"id","type"}},
{ "embed", new List<string>() {"src","type","wmode"}}
};
I believe the answer is that VB.NET 3.5 does not support collection initialization syntax.
VB.NET in .NET 4 does support collection initializers as follows:
Dim days = New Dictionary(Of Integer, String) From
{{0, "Sunday"}, {1, "Monday"}}
The previous code example is equivalent to the following code.
Dim days = New Dictionary(Of Integer, String)
days.Add(0, "Sunday")
days.Add(1, "Monday")
You want something like this (for .NET 3.5):
Shared Sub New()
Dim dict As New Dictionary(Of String, List(Of String))
Dim l1 As New List(Of String)
l1.Add("name")
l1.Add("value")
dict.Add("param", l1)
Dim l2 As New List(Of String)
l2.Add("id")
l2.Add("type")
dict.Add("object", l2)
Dim l3 As New List(Of String)
l3.Add("src")
l3.Add("type")
l3.Add("wmode")
dict.Add("embed", l3)
MyClass.ValidHtmlTags = dict
End Sub
Private Shared ReadOnly ValidHtmlTags As Dictionary(Of String, List(Of String))
Private Shared ReadOnly ValidHtmlTags As Dictionary(Of String, List(Of String)) = New Dictionary(Of String, List(Of String))
Then somewhere in a Sub or a Function:
ValidHtmlTags.Add("param", New List(Of String))
ValidHtmlTags("param").Add("name")
ValidHtmlTags("param").Add("value")
ValidHtmlTags.Add("object", New List(Of String))
ValidHtmlTags("object").Add("id")
ValidHtmlTags("object").Add("type")
ValidHtmlTags.Add("embed", New List(Of String))
ValidHtmlTags("embed").Add("src")
ValidHtmlTags("embed").Add("type")
ValidHtmlTags("embed").Add("wmode")
There are a few decent C# <--> VB.NET converts online as well. I use http://www.developerfusion.com/tools/convert/csharp-to-vb/ to get:
Private Shared ReadOnly ValidHtmlTags As New Dictionary(Of String, List(Of String))()
Then build each List(Of String) and add to ValidHtmlTags separately. eg.
Dim paramList As New List(Of String)()
paramList.Add("name")
paramList.Add("value")
ValidHtmlTags.Add("param", paramList)
I'm not sure you can pass in a list of values into the List(Of String) constructor in VB.NET.
精彩评论