在ConcurrentDictionary中插入值

Mar*_*ark 4 c#-4.0

我正在尝试将值插入ConcurrentDictionary,我习惯于字典,所以这不起作用:

  public ConcurrentDictionary<string, Tuple<double, bool,double>> KeyWords =  new
                ConcurrentDictionary<string, Tuple<double, bool,double>>
    {
        {"Lake", 0.5, false, 1}
    };
Run Code Online (Sandbox Code Playgroud)

什么是正确的方式,因此我正在上课.

LBu*_*kin 10

集合初始化程序是用于调用公共Add()方法的语法糖...它ConcurrentDictionary没有提供 - 它有一个AddOrUpdate()方法.

您可以使用的替代方法是Dictionary<>传递给构造函数重载的中间函数,该重载函数接受IEnumerable<KeyValuePair<K,V>>:

public ConcurrentDictionary<string, Tuple<double, bool,double>> KeyWords =  
    new ConcurrentDictionary<string, Tuple<double, bool,double>>( 
       new Dictionary<string,Tuple<double,bool,double>>
       {
          {"Lake", Tuple.Create(0.5, false, 1.0)},
       } 
    );
Run Code Online (Sandbox Code Playgroud)

注意:我更正了您的示例以使用,Tuple.Create()因为元组不是来自初始化器.


Joh*_*son 5

您可以使用字典初始值设定项

var dict = new ConcurrentDictionary<int, string>
    {
        [0] = "zero",
        [1] = "one",
    };
Run Code Online (Sandbox Code Playgroud)

是的,我知道问题是