无法隐式转换System.Collections.Generic.Dictionary <string,system.collections.generic.list <string>&gt;&#39; to&#39; System ... <string,string>&#39; </string,string> </string,system.collections.generic.list <string>

时间:2015-02-05 21:16:12

标签: c#

class Program
{
    static void Main(string[] args)
    {           
        Dictionary<string, string> questionDict = new Dictionary<string, List<string>>(); //creating animal dict
        List<string> removeKeys = new List<string>(); //so I can remove the keys if need be
        questionDict.Add("Does it have whiskers?", "cat");
        questionDict.Add("Does it purr?", "cat");
        questionDict.Add("Does it bark?", "dog");
        while (true)
        {
            foreach (KeyValuePair<string, string> kvp in questionDict)//checks for each value of kvp in questionDict
            {
                Console.WriteLine("Computer: {0}", kvp.Key); //prints kvp, or in this instance, the question
                string userInput = Console.ReadLine();
                if (userInput.ToLower() == "yes") //if yes THEN
                {
                    Console.WriteLine("VAL: {0}", kvp.Value); //writes the value
                }
                else
                {
                    removeKeys.Add(kvp.Key); //adds the wrong animals to the removeKeys list
                }
            }
            foreach(string rKey in removeKeys)
            {
                questionDict.Remove(rKey); //removes all the values of rKey in removeKeys from questionDict
            }
        }
    }
}

new Dictionary<string, List<string>>();给了我错误。有帮助吗?我试图让我的字典每个键有多个值,我被告知只能通过List<string>来实现。

1 个答案:

答案 0 :(得分:3)

将您的声明更改为:

Dictionary<string, List<string>> questionDict = new Dictionary<string, List<string>>();

被赋值的变量的泛型参数必须与您实例化的变量相匹配。该类型当然也必须匹配(它已经做到了)。请确保对其他适用的代码段进行此更正,例如foreach循环定义。

注意,如果你喜欢var(即使你没有,这是可以使用的更好的地方之一)你可以写:

var questionDict = new Dictionary<string, List<string>>();

哪个更短,更难搞乱!