2017-04-21 52 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

非常感谢。 –

相关问题