sourcetip

선언 시 사전에 키/값 추가

fileupload 2023. 5. 28. 21:00
반응형

선언 시 사전에 키/값 추가

오늘은 아주 쉬운 것 같아요.C#에서 다음과 같이 사용됩니다.

Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } };

하지만 vb에서는 다음이 작동하지 않습니다.

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("",""))

선언할 때 그것들을 추가할 수 있는 방법이 있다고 꽤 확신하지만, 어떻게 하는지는 잘 모르겠습니다.그리고 예, 다른 시간이 아닌 선언 시에 추가하고 싶습니다.:) 그래서 가능하기를 바랍니다.여러분 감사합니다.

저도 해봤어요.

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""})

그리고...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")}

그리고...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}}

이는 VB.NET 10에서 가능합니다.

Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }}

안타깝게도 IIRC VS 2008은 이 구문을 지원하지 않는 VB.NET 9 컴파일러를 사용합니다.

그리고 관심을 가질 만한 사람들을 위해 다음과 같은 일이 발생합니다(C#).

Dictionary<int, string> VB$t_ref$S0 = new Dictionary<int, string>();
VB$t_ref$S0.Add(1, "Test1");
VB$t_ref$S0.Add(2, "Test1");
Dictionary<int, string> dict = VB$t_ref$S0;

거의 동일합니다. 다음을 사용합니다.From키워드:

    Dim d As New Dictionary(Of String, String) From {{"", ""}}

그러나 이를 위해서는 VS2010에서 사용할 수 있는 언어 버전 10이 필요합니다.

여기 멋진 번역이 있습니다.또한 문자열 및 문자열 배열의 일반 사전을 가질 수 있습니다.

C#:

private static readonly Dictionary<string, string[]> dics = new Dictionary<string, string[]>
{
    {"sizes", new string[]  {"small", "medium", "large"}},
    {"colors", new string[]  {"black", "red", "brown"}},
    {"shapes", new string[]  {"circle", "square"}}
};

VB:

Private Shared ReadOnly dics As New Dictionary(Of String, String()) From {
 {"sizes", New String() {"small", "medium", "large"}},
 {"colors", New String() {"black", "red", "brown"}},
 {"shapes", New String() {"circle", "square"}}}

멋진 하하 :)

사전의 키 값 쌍을 가져올 생성자가 없습니다.

언급URL : https://stackoverflow.com/questions/3771922/add-keys-values-to-dictionary-at-declaration

반응형