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

初始化C#标签的最简洁方法[重复]

  •  50
  • RexE  · 技术社区  · 17 年前

    C#是否允许在一行表达式中填充哈希表?我在想一个相当于下面Python的东西:

    mydict = {"a": 23, "b": 45, "c": 67, "d": 89}
    

    1 回复  |  直到 17 年前
        1
  •  75
  •   Community Mohan Dere    9 年前

    集合初始化器 它允许您在一条语句中初始化集合的值。

    下面是一个使用 Dictionary<,> :

    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main()
        {
            var dict = new Dictionary<string, int>
            {
                {"a", 23}, {"b", 45}, {"c", 67}, {"d", 89}
            };
        }
    }
    

    IEnumerable 并拥有公众 Add 方法。

    this question I asked here on StackOverflow C#团队以一种奇怪的方式实现了这个语言扩展(一旦你阅读了这个问题的优秀答案,你就会发现它很有意义)。