12
在Python可以做的:C#的类似Python的字典声明?
d = {1 : 'Hello', 2 : 'World'}
在C#中它更详细:
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, 'Hello');
d.Add(2, 'World');
我怎样才能使这个更简洁一些?
在Python可以做的:C#的类似Python的字典声明?
d = {1 : 'Hello', 2 : 'World'}
在C#中它更详细:
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, 'Hello');
d.Add(2, 'World');
我怎样才能使这个更简洁一些?
可以使用collection initializer syntax(和implicit typing with var
):
var myDict = new Dictionary<int, string> { {1, "Hello"}, {2, "World"} };
此代码实际上将被编译成你有上面的代码。请注意,您(不幸)不能忽略构造函数或泛型类型参数。
不是Pythonic,但到达那里!