2017-04-21 53 views
-7

的問題是C#:不能隱式轉換類型「字符串」到「廉政」錯誤

return playerInfo[name][timetype]; 

線。我不知道什麼是錯的。

using UnityEngine; 
    using System.Collections; 
    using UnityEngine.UI; 
    using System.Linq; 
    using System.Collections.Generic; 
    // scoreboard 
    public class bandau : MonoBehaviour 
    { 
     Dictionary<string, Dictionary<string, string>> playerInfo; 

     // Use this for initialization 
     void Start() 
     { 
      SetName("po", "time", "0220"); 
      Debug.Log(GetName("po", "time")); 
     } 

     void Init() // to do then its needs to be done 
     { 
      if (playerInfo != null) 
      { 
       playerInfo = new Dictionary<string, Dictionary<string, string>>(); 
      } 
     } 

     public int GetName(string name, string timetype) 
     { 
      Init(); 

      if (playerInfo.ContainsKey(name) == false) 
      { 
       return 0; 
      } 

      if (playerInfo[name].ContainsKey(timetype) == false) 
      { 
       return 0; 
      } 

      return playerInfo[name][timetype]; //Where is the problem? 
     } //function to get player name ant other parameters 

     public void SetName(string name, string timetype, string value) 
     { 
      Init(); 

      if(playerInfo.ContainsKey(name) == false) 
      { 
       playerInfo[name] = new Dictionary<string, string>(); 
      } 

      playerInfo[name][timetype] = value; 
     } // set player values 

     public void ChangeName(string name, string timetype, string amount) 
     { 
      Init(); 
      int currName = GetName(name, timetype); 
      SetName(name, timetype, currName + amount); 
     } // if needs to be changed 

     // Update is called once per frame 
     void Update() 
     { 
     } 
} 
+3

'GetName'的返回類型是'int'。這聽起來應該是'string'。 –

+1

顯然'playerInfo [name] [timetype]'是一個字符串,你將它作爲整型返回值返回。 –

+0

顯然'playerInfo [name] [timetype]'是一個'string'。正如錯誤告訴你的那樣。 – David

回答

4

playerInfoDictionary<string, Dictionary<string, string>>的類型。這意味着playerInfo[name][timetype]將是一個字符串。

你的方法GetName有簽名public int GetName(string name, string timetype)它說它返回一個int。但是,在該方法的末尾,您有return playerInfo[name][timetype];這意味着對於期望您返回int的方法實際上是試圖返回一個字符串。因此,編譯器告訴你它試圖將字符串轉換爲一個int,但無法執行,因爲沒有隱式轉換。

+1

非常感謝。 –

相關問題