2015-02-05 284 views
-2
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>来实现。无法隐式转换 'System.Collections.Generic.Dictionary <字符串,System.Collections.Generic.List <string>>' 到 '系统... <字符串,字符串>'

+2

错误的哪部分你不明白?看看那条线的两边。 – SLaks 2015-02-05 21:17:29

+0

那么,你刚刚在同一行上说过你想要一个字典。 – 2015-02-05 21:17:40

回答

3

更改您的声明:

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

赋值的变量的通用参数必须匹配那些你实例化什么的。这种类型当然也必须匹配(它已经做到了)。请确保将此更正修改为其他您的代码的相应部分,例如您的foreach循环定义。

注意,如果你喜欢VAR(即使你不这样做,这是更好的地方可以使用的一个),你可以这样写:

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

这更短,很难搞砸!

+0

或只是使用变种 – Casey 2015-02-05 21:25:46

+0

是的,这将使这个错误更难以进入(即使我通常不使用变种:)) – BradleyDotNET 2015-02-05 21:26:18

+0

嗯,我是一个很大的粉丝,但即使你不是你有承认这是您可以使用的最不具争议的方式之一。 – Casey 2015-02-05 21:27:15

相关问题