簡體   English   中英

初始化字典里面的字典 C# vs Python

[英]Initialize dictionary inside dictionary C# vs Python

為什么字典中的字典需要在 c# 中明確顯示,例如,請參閱以下代碼 d1、d2 很好,但在 d3 編譯器上會出現問題。

var d1 = new Dictionary<string, string> { { "1", "1" } }; //works
var d2 = new Dictionary<string, Dictionary<string, string>> { { "1", d1 } }; //works
var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", { { "1", "1" } } }} //does not work

Python 做同樣和更簡單的方法

d1:dict={'1':1}
d2:dict = {'1':{'1':1}}

您已經遺漏了new Dictionary<string, string>部分(和一個結束} ):

var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", new Dictionary<string, string> { { "1", "1" } } } };
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−^

您需要告訴 C# 要創建的具體實例,因為您可能正在使用Dictionary子類:

class SomeDictionarySubclass<K, V> : Dictionary<K, V> {
    // ...
}
// ...
var d3 = new Dictionary<string, Dictionary<string, string>> {
    { "1", new SomeDictionarySubclass<string, string> { { "1", "1" } } }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM