C#:无法隐式转换类型' string'到' int'错误

时间:2017-04-21 12:15:28

标签: 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()
        {
        }
}

1 个答案:

答案 0 :(得分:4)

playerInfo的类型为Dictionary<string, Dictionary<string, string>>。这意味着playerInfo[name][timetype]将是一个字符串。

您的方法GetName具有签名public int GetName(string name, string timetype),表示它正在返回int。但是在该方法结束时,您有return playerInfo[name][timetype];这意味着对于期望返回int的方法实际上是尝试返回一个字符串。因此,编译器会告诉您它正在尝试将字符串转换为int但无法进行,因为没有隐式转换。