代码之家  ›  专栏  ›  技术社区  ›  Casebash

字典初始化语法说明(C)

c#
  •  2
  • Casebash  · 技术社区  · 14 年前

    我发现了一个例子,表明一本字典可以初始化如下:

    Dictionary<string, int> d = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };
    

    我不懂语法 {"cat", 2} 对于创建键值对有效。集合初始化语法的形式似乎是 new MyObjType(){} ,而匿名对象的形式为 {a="a", b="b"} . 这里到底发生了什么?

    4 回复  |  直到 14 年前
        1
  •  7
  •   caesay    14 年前

    好吧,让我们看看这里的代码:

    Dictionary<string, int> d = new Dictionary<string, int>() 
    { 
        {"cat", 2}, 
        {"dog", 1}, 
        {"llama", 0}, 
        {"iguana", -1} 
    };
    

    字典包含两个东西,一个键和一个值。 你的声明, Dictionary<string, int> ,表示键是字符串,值是整数。

    现在,当您添加一个项目时,例如 {"cat", 2}, ,关键是cat。这就相当于你做了, d.Add("cat", 2); . 字典可以容纳任何东西,从 <string, string> <customClass, anotherCustomClass> . 打电话给你可以用 int CAT = d["cat"]; 价值 int CAT 将是2。例如:

    Dictionary<string, int> dict = new Dictionary<string, int>() 
    { 
        {"cat", 1}
    };
    dict.Add("dog", 2);
    Console.WriteLine("Cat="+dict["cat"].ToString()+", Dog="+dict["dog"].ToString());
    

    在那里,你添加了不同价值观的猫和狗,并把它们叫来

        2
  •  1
  •   Vlad    14 年前

    Dictionary 是一个 ICollection 属于 KeyValuePair S. {"cat", 2} 是一个 键值空气 .

        3
  •  1
  •   JoshJordan    14 年前

    我不确定您的问题是什么,但答案是,这是集合初始化的语法,它为添加方法提供了快捷方式。

    这也适用,例如:

    new List<DateTime>()
    {
        {DateTime.Now},
        {new DateTime()},
        {DateTime.Now}
    }
    

    通常当问题是“为什么这个有效”时,答案是因为“它是有效的”:)

    请注意,在问题的后一部分中指定的语法不仅适用于匿名对象,还适用于具有公共属性设置器的任何对象:

    new MyPerson("Bob")
    {
        Address = "185 What St",
        DoB = DateTime.Now
    }
    
        4
  •  0
  •   Tim C    14 年前

    这是一个关键的价值组合。这个 Dictionary<string,int> 说钥匙是 string 值将是 int . 从而 {"cat", 2} 你有一把钥匙 "cat" 和一个值 2 . 我不确定为什么您会有一个cat的键和一个2的值,但它始终是一个字典的例子,它有一个字符串键和一个int值。更多信息和示例可在此处找到:

    MSDN Dictionary<> with Examples