2011-09-08 10 views
12
1が行うことができますPythonで

:C#のでC#のPythonのような辞書宣言?

d = {1 : 'Hello', 2 : 'World'} 

それはより冗長です:

Dictionary<int, string> d = new Dictionary<int, string>(); 
d.Add(1, 'Hello'); 
d.Add(2, 'World'); 

は、どのように私は、これはそれほど冗長することができますか?

答えて

22

あなたはcollection initializer syntax(およびimplicit typing with var)を使用することができます。

var myDict = new Dictionary<int, string> { {1, "Hello"}, {2, "World"} }; 

このコードは、実際にあなたが持っている上記のコードにまでコンパイルされます。残念ながら、コンストラクタやジェネリック型の引数は削除できません。

かなりPythonicですが、そこに着いています!