2015-02-05 283 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

相關問題