首页 > 解决方案 > 字典初始值设定项的类型

问题描述

我有这个代码:

class Program
{
    static void Main(string[] args)
    {
        var a = new Dictionary<string, int>()
        {
            { "12", 12 },
            { "13", 13 },
        };
    }

    static object Fifteen()
    {
        //return new object[] { "15", 15 };
        return new {key = "15", value = 15};
    }
}

如何编写Fifteen以便可以将其添加到初始化程序?

我想要这个,编译:

        var a = new Dictionary<string, int>()
        {
            { "12", 12 },
            { "13", 13 },
            Fifteen()
        };

LE 编译错误是:error CS7036: There is no argument given that corresponds to the required formal parameter 'value' of 'Dictionary<string, int>.Add(string, int)'

标签: c#dictionary

解决方案


您需要更改您的方法Fifteen,使其返回 aKeyValuePair而不是object它们被创建):

static KeyValuePair<string, int> Fifteen()
{
    return new KeyValuePair<string, int>("15", 15);
}

然后你需要添加一个扩展方法,Dictionary以便它有一个Add接受一个KeyValuePair而不是两个参数的方法:

public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, KeyValuePair<TKey, TValue> pair)
{
    dictionary.Add(pair.Key, pair.Value);
}

之后,您声明的代码编译并运行得很好。


推荐阅读