C# 通过其容器的内联初始化向字典添加值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10998961/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:03:56  来源:igfitidea点击:

Adding values to a dictionary via inline initialization of its container

c#dictionaryinitialization

提问by Timothée Bourguignon

I have the following Cityclass. Each city object contains a dictionary which keys are language tags (let's say: "EN", "DE", "FR"...) and which values are the city names in the corresponding languages (ex: Rome / Rom etc.).

我有以下City课程。每个城市对象都包含一个字典,其中的键是语言标签(比方说:“EN”、“DE”、“FR”...),哪些值是相应语言的城市名称(例如:Rome / Rom 等) .

public class City:
{
  private IDictionary<string, string> localizedNames = new Dictionary<string, string>(0);
  public virtual IDictionary<string, string> Names
  {
    get { return localizedNames ; }
    set { localizedNames = value; }
  }
}

Most of the cities have the same names whatever the language so the Cityconstructor does actually creates the English mapping:

无论使用何种语言,大多数城市都具有相同的名称,因此City构造函数实际上创建了英文映射:

  public City(string cityName)
  {
    this.LocalizedNames.Add("EN", cityName);
  }

Here comes the question: is there a way to add the other values via inline initialization?

问题来了:有没有办法通过内联初始化添加其他值?

I tried different variations of the following without semantic success (does not compile):

我尝试了以下不同的变体,但没有语义成功(不编译):

AllCities.Add(new City("Rome") { Names["DE"] = "Rom" };

I also tried creating a new Dictionary, but this obviously overwrites the "EN" parameter:

我也尝试创建一个新的字典,但这显然覆盖了“EN”参数:

AllCities.Add(new City("Rome") { Names = new Dictionary<string, string>() { { "DE", "Rom" } } };

Anybody know if this is possible?

有谁知道这是否可能?

采纳答案by usr

AllCities.Add(new City("Rome") { Names = { { "DE", "Rom" }, { "...", "..." } } });

This is using initializer syntax to invoke the .Add method.

这是使用初始化语法来调用 .Add 方法。

回答by zafar

this is actual inline intialization:

这是实际的内联初始化:

private IDictionary<string, string> localizedNames = new Dictionary<string, string>{
    {"key1","value1"},
    {"key2","value2"}
};