开发者

Python-like dictionary declaration for C#?

开发者 https://www.devze.com 2023-04-03 08:28 出处:网络
In Python one can do: d = {1 : \'Hello\', 2 : \'World\'} In C# it\'s more verbose: Dictionary<int, string> d = new Dictionary<开发者_如何学Python;int, string>();

In Python one can do:

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

In C# it's more verbose:

Dictionary<int, string> d = new Dictionary<开发者_如何学Python;int, string>();
d.Add(1, 'Hello');
d.Add(2, 'World');

How can I make this less verbose?


You can use the collection initializer syntax (and implicit typing with var):

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

This code will actually be compiled down to the code you have above. Note that you (unfortunately) can't elide the constructor or the generic type arguments.

Not quite Pythonic, but getting there!

0

精彩评论

暂无评论...
验证码 换一张
取 消