简体   繁体   中英

CS1950 The best overloaded add method Dictionary<string,Func<string>) for the collection initializer has some invalid arguments

I am running into this error.. not sure what I am missing. This is reproducible code.

Sorry for the edit on the question- What if I wish to pass 2 strings to the function?

  class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        string myString = "test";
        string testString = "test";

        IDictionary<string, Func<string>> identityInformation = new Dictionary<string, Func<string>>
    {
        { "text1", () => {return test(myString, testString); } },
        { "text2", () => { return test(myString, testString); } }
    };

}
    public static string test(string myString, string testString)
    {
        return myString;
    }

}

EDIT based on comments you can go with option A and call method when adding item into dictionary

string myString = "test";
string testString = "test";
var identityInformation = new Dictionary<string, string>
{
    { "text1", test(myString, testString) },
    { "text2", test(myString, testString) }
};

public static string test(string myString, string testString)
{
    return myString;
}

Not sure which is defined interface you need to follow. There are multiple ways to fix it. Because Func it has no parameters and returns string, which test method is not. Therefore:

A- Change dictionary to store results

 Dictionary<string, string>

B- change signature of dictionary to Func<string,string> and store delegates. Then myString as parameter will be used later.

IDictionary<string, Func<string,string>> identityInformation = new Dictionary<string, Func<string,string>>
{
    { "text1", test },
    { "text2", test }
};

C- add lambda

IDictionary<string, Func<string>> identityInformation = new Dictionary<string, Func<string>>
{
    { "text1", () => test(myString) },
    { "text2", () => test(myString) }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM