无法将类型 'string' 隐式转换为 'int'

Cannot implicitly convert type 'string' to 'int'

我正在做一个运动员项目,我想制作 int salaryCounter = athleteSalary.ToString 所以当用户输入聘用专业人员的工资时,我可以从运动员的工资中减去它并打印出如何运动员将离开很多,但当我尝试这样做时,程序告诉我 "Cannot implicitly convert type 'string' to 'int' "。有人可以帮助我吗?

{
    Console.WriteLine("Please enter the first name of the athlete");
    String athleteString = Console.ReadLine();
    Console.WriteLine("Please enter the second name of the athlete");
    String athleteString2 = Console.ReadLine();
    Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", athleteString.ToString(), athleteString2.ToString());
    ConsoleKeyInfo KeyInfo = Console.ReadKey();

    if (KeyInfo.KeyChar == 'y')
    {
        Console.WriteLine("Enter the salary of {0} {1}", athleteString.ToString(), athleteString2.ToString());
        String athleteSalary = Console.ReadLine();
        Console.WriteLine("{0} Is this right?", athleteSalary.ToString());
        ConsoleKeyInfo rightathleteSalary = Console.ReadKey();
        int salaryCounter = athleteSalary.ToString();

        if (rightathleteSalary.KeyChar == 'y')
        {
             Console.WriteLine("Ok. Lets contiune.");
             athleteSalary = Convert.ToString(salaryCounter);
             Console.WriteLine(salaryCounter);

             int counter = 0;

             Console.WriteLine("{0} {1} {2}", athleteString.ToString(), athleteString2.ToString(), salaryCounter.ToString());
             Console.WriteLine("Enter the hired help. The max number of people is five. Press any key to start.");

             while (counter < 5)
             {
                 Console.ReadKey();
                 Console.WriteLine("Please enter the first name of the hired help");
                 String hiredhelpString = Console.ReadLine();
                 Console.WriteLine("Please enter the Last name of the hired help");
                 String hiredhelpString2 = Console.ReadLine();
                 Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
                 ConsoleKeyInfo KeyInfo5 = Console.ReadKey();

                 if (KeyInfo5.KeyChar == 'y')
                 {
                     Console.WriteLine("Enter the salary of {0} {1}", hiredhelpString.ToString(), hiredhelpString2.ToString());
                     String hiredhelpSalary = Console.ReadLine();
                     Console.WriteLine("{0} Is this right?", hiredhelpSalary.ToString());
                     ConsoleKeyInfo rightSalary = Console.ReadKey();

                     if (rightSalary.KeyChar == 'y')
                     {
                         Console.WriteLine("Ok. Lets contiune.");
                     }
                     Console.WriteLine("Record this proffesional? Press y for yess n for no.");
                     ConsoleKeyInfo RecordKey = Console.ReadKey();

                     if (RecordKey.KeyChar == 'y')
                     {
                         counter = counter + 1;
                         Console.WriteLine("Number of hired help is {0} They will be paid {1}", counter, hiredhelpSalary);
                         Console.WriteLine("Press any key to contiune.");
                     }
                     else
                     {
                         if (RecordKey.KeyChar == 'n')
                         {
                             counter = counter - 1;
                             Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
                             Console.ReadKey();
                             Console.WriteLine("Please enter the first name of the hired help");
                             String hiredhelpString3 = Console.ReadLine();
                             Console.WriteLine(" Please enter the Last name of the hired help");
                             String hiredhelpString4 = Console.ReadLine();
                             Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
                             ConsoleKeyInfo KeyInfo6 = Console.ReadKey();

                             if (KeyInfo6.KeyChar == 'y')
                             {
                                 Console.WriteLine("Record this proffesional? Press y for yess n for no.");
                                 ConsoleKeyInfo RecordKey1 = Console.ReadKey();
                                 if (RecordKey.KeyChar == 'y')
                                 {
                                     counter = counter + 1;
                                     Console.WriteLine("Number of Hired help is {0} press any key to contiune", counter);
                                     Console.WriteLine("Press any key to contiune.");
                                 }
                             }
                         }
                     }
                            /*******************************************************************************************************/
                            /************************************************************************************************************************************************************************************************************************************************/
                        }
                        else
                        {
                            if (KeyInfo5.KeyChar == 'n')
                            {
                                Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
                                Console.ReadKey();

                            }
                        }
                    }
                    /*************************************************************************************************************************************************************************************************************************************/
                    Console.WriteLine("");
                    Console.WriteLine("Athlete's name: {0} {1} Number of Hired help is {2}", athleteString.ToString(), athleteString2.ToString(), counter);
                    Console.ReadKey();


            }

您似乎对变量类型感到困惑。简要地;

string - 逐字符存储信息。编译器无法读取存储在字符串中的数字。

int - 存储可用于计算的整数值。

您的直接编译问题来自这一行;

int salaryCounter = athleteSalary.ToString();

您要告诉编译器获取字符串 altheteSalary,调用获取字符串表示形式的 ToString() 方法(当源是字符串时这是不必要的)并将结果存储为整数。

您需要解析字符串才能像这样读出数值;

int salaryCounter = int.Parse(athleteSalary)

不过,无论何时直接从用户接收输入,您都应该进行防御性编码,因此不要使用 int.Parse,而是使用 TryParse。这样,如果您的用户输入 'Bob' 作为他们的薪水,您可以显示适当的错误;

int salaryCounter;
while(!int.TryParse(athleteSalary, out salaryCounter)
{
    Console.Writeline("The salary should be a number, try again");
    athleteSalary = Console.ReadLine();
}

此外,您可以删除对 .ToString() 的大部分调用,尤其是在变量已经是字符串的情况下。

主要问题是您需要将用户输入转换为字符串以外的类型。

有很多方法可以做到这一点,但由于您正在编写一个严重依赖用户输入数据的控制台应用程序,并且由于其中一些数据必须转换为字符串以外的类型,您可以考虑编写一些辅助方法可以为您处理一些转换和重试。

我已经在多个应用程序中成功使用了以下 class。基本上,它只是一堆接受字符串 'prompt' 和 return 来自用户的强类型结果的方法。如果用户输入无效数据,则他们必须重试,直到输入有效数据:

class UserInput
{
    public static bool GetBool(string prompt)
    {
        bool result;

        List<string> validTrueResponses = 
            new List<string> {"yes", "y", "true", "t", "affirmative", 
                "ok", "okay", "yea", "yeah", "yep"};

        List<string> validFalseResponses = 
            new List<string> {"no", "n", "false", "f", "negative", 
                "never", "not", "nay", "nix"};

        while (true)
        {
            if (prompt != null) Console.Write(prompt);
            var input = Console.ReadLine();

            if (validTrueResponses.Any(r => 
                r.Equals(input, StringComparison.OrdinalIgnoreCase))) return true;

            if (validFalseResponses.Any(r => 
                r.Equals(input, StringComparison.OrdinalIgnoreCase))) return false;

            if (bool.TryParse(input, out result)) break;

            Console.WriteLine("Sorry, I don't understand that response. " +
                "Please try again.");
        }

        return result;
    }

    public static string GetString(string prompt)
    {
        if (prompt != null) Console.Write(prompt);
        return Console.ReadLine();
    }

    public static int GetInt(string prompt)
    {
        int input;

        while (true)
        {
            if (prompt != null) Console.Write(prompt);
            if (int.TryParse(Console.ReadLine(), out input)) break;
            Console.WriteLine("Sorry, that is not valid. Please try again.");
        }

        return input;
    }

    public static decimal GetDecimal(string prompt)
    {
        decimal input;

        while (true)
        {
            if (prompt != null) Console.Write(prompt);
            if (decimal.TryParse(Console.ReadLine(), out input)) break;
            Console.WriteLine("Sorry, that is not valid. Please try again.");
        }

        return input;
    }
}

然后,我将创建一个简单的 class 来表示 Person,它只有名字、姓氏和薪水(并覆盖 ToString 方法以显示名字和姓氏):

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Salary { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }
}

现在我们可以通过创建获取Person姓名和薪水的方法来减少一些重复代码。这将提示用户输入信息,然后让他们有机会在提交数据之前更正它:

private static void GetPersonName(Person person, string typeOfPerson)
{
    if (person == null) throw new ArgumentNullException("person");
    if (string.IsNullOrWhiteSpace(typeOfPerson)) typeOfPerson = "person";

    bool inputIsGood = false;

    while (!inputIsGood)
    {
        person.FirstName = UserInput.GetString(
            string.Format("Please enter the first name of the {0}: ", typeOfPerson));

        person.LastName = UserInput.GetString(
            string.Format("Please enter the last name of the {0}: ", typeOfPerson));

        Console.WriteLine("You entered: {0}", person);
        inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
    }
}

private static void GetPersonSalary(Person person)
{
    bool inputIsGood = false;

    while (!inputIsGood)
    {
        person.Salary = UserInput.GetDecimal(
            string.Format("Enter the salary of {0}: $", person));

        Console.WriteLine("You entered: {0:C}", person.Salary);
        inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
    }
}

这可能看起来像很多代码,但您可以通过以下方式在您的应用程序中使用它:

private static void Main()
{
    var athlete = new Person();

    GetPersonName(athlete, "athlete");
    GetPersonSalary(athlete);

    Console.WriteLine("Enter the hired help. The max number of people is five. " +
        "Press any key to start.");

    Console.ReadKey();

    List<Person> hiredHelpers = new List<Person>();

    while (hiredHelpers.Count <= 5)
    {
        bool addAnotherHelper =
            UserInput.GetBool(
                string.Format("There are currently {0} helpers. " +
                    "Do you want to add another (y/n): ",
                    hiredHelpers.Count));

        if (!addAnotherHelper) break;

        Person helper = new Person();

        GetPersonName(helper, "helper");
        GetPersonSalary(helper);

        bool recordHelper = UserInput.GetBool("Do you want to record this " +
            "professional (y/n): ");

        if (recordHelper)
        {
            hiredHelpers.Add(helper);
        }
    }

    Console.WriteLine();
    Console.WriteLine("Athlete's name: {0}, salary: {1:C}.", athlete, athlete.Salary);
    Console.WriteLine("Number of Hired help is: {0}", hiredHelpers.Count);
    Console.WriteLine("Hired help details:");
    hiredHelpers.ForEach(h => 
        Console.WriteLine(" - Name: {0}, Salary: {1:C}", h, h.Salary));

    Console.ReadKey();
}