我有一个方法,它将Dictionary<int, int>
作为参数
public void CoolStuff(Dictionary<int, int> job)
我想用一个字典条目调用该方法,例如
int a = 5;
int b = 6;
var param = new Dictionary<int, int>();
param.Add(a, b);
CoolStuff(param);
我怎样才能在一行中完成?
答案 0 :(得分:63)
就是这样,如果您不需要a
和b
变量:
var param = new Dictionary<int, int> { { 5, 6 } };
甚至
CoolStuff(new Dictionary<int, int> { { 5, 6 } });
请阅读How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)
答案 1 :(得分:10)
var param = new Dictionary<int, int>() { { 5, 6 } };