字典初始值设定项的类型

fox*_*337 3 c# dictionary

我有这个代码:

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};
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我想要这个,编译:

        var a = new Dictionary<string, int>()
        {
            { "12", 12 },
            { "13", 13 },
            Fifteen()
        };
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*rvy 14

您需要更改Fifteen方法,以便它返回a KeyValuePair而不是a object,以便方法的调用者可以访问您提供的数据(匿名类型只应在它们以相同的方法使用时使用他们被创造了):

static KeyValuePair<string, int> Fifteen()
{
    return new KeyValuePair<string, int>("15", 15);
}
Run Code Online (Sandbox Code Playgroud)

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

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

之后您的声明代码编译并运行正常.