首页 > 解决方案 > 我不明白 C# 中的字符串

问题描述

作为只使用过c++的人,我很困惑。我已经阅读了不同的解释,但我似乎仍然无法理解。例如,为什么我需要检查一个字符串是否是一个字符串?(tryparse 方法)如果它显然是一个数字,它是一个 int ......对吗?因此,例如,我当前的代码在一个函数中获取年龄并将其输出到主函数中。我尝试将其转换为 int,但出现错误 cs0019: Operator '==' cannot be applied to operands of 'int' and 'string'

public static string GetAge()
{
  Console.WriteLine("\nPlease input age > ");

int age = Int32.Parse(Console.ReadLine());
  if (age == "") 
  {
    do {
      Console.Write("Invalid input. Please try again > ");
      age = Console.ReadLine();
       } while ( age == "");
  }
  return age;

}

static void Main (){

Console.WriteLine("\nPlease note\nThis program is only applicable for users born between 1999 and 2010");

string name = GetName();
string year = GetYear();
int age = GetAge();

然后我也收到此错误 cs0029:无法将类型“int”隐式转换为“字符串”(第 49 行是返回年龄)和错误 cs0029:无法将第 58 行的类型“字符串”隐式转换为“int”(int age =获取年龄();)

标签: c#

解决方案


int.Parse如果失败会抛出异常。我会将您的循环修改为:

int age; 
while (!int.TryParse(Console.ReadLine(), out age))
    Console.Write("Invalid input. Please try again > ");
return age;

int.TryParse成功后将返回true

还要更改方法定义以返回一个int

public static int GetAge()

推荐阅读