C# 6 元组应用 Part 1:方便的字典工厂方法

首先是简单的实现:

    public static class CollectionExtensions
    {

        public static IDictionary<TKey, TValue> Map<TKey, TValue>(params (TKey key, TValue value)[] pairs)
        {
            var dict = new Dictionary<TKey, TValue>(pairs.Length);
            foreach (var p in pairs)
            {
                dict.Add(p.key, p.value);
            }
            return dict;
        }

    }

然后就是简单的调用了:

using static CollectionExtensions;

void Main() {
    var dict = Map(("Name", "John Doe"), ("Address", "Wall Street"));
}

感觉是不是比 C# 语法内置的 Dictionary Literal 要清爽不少:

var dict = new Dictionary<string, string> {
    { "Name", "John Doe" },
    { "Address", "Wall Street" }
};

 

  

posted on 2017-06-25 11:44  李屠户  阅读(373)  评论(0编辑  收藏  举报