C# One-liner 创建一个包含一个条目的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14454929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
One-liner to create a dictionary with one entry
提问by Michael Sandler
I have a method which takes a Dictionary<int, int>
as a parameter
我有一个将 aDictionary<int, int>
作为参数的方法
public void CoolStuff(Dictionary<int, int> job)
I want to call that method with one dictionary entry, such as
我想用一个字典条目调用该方法,例如
int a = 5;
int b = 6;
var param = new Dictionary<int, int>();
param.Add(a, b);
CoolStuff(param);
How can I do it in one line?
我怎样才能在一行中做到这一点?
采纳答案by horgh
This is it, if you do not need the a
and b
variables:
就是这样,如果您不需要a
和b
变量:
var param = new Dictionary<int, int> { { 5, 6 } };
or even
甚至
CoolStuff(new Dictionary<int, int> { { 5, 6 } });
Please, read How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)
回答by Sergey Berezovskiy
var param = new Dictionary<int, int>() { { 5, 6 } };