C# 我不知道';我不懂c中的字符串# 作为一个只使用C++的人,我很困惑。我看了不同的解释,但似乎还是不明白。例如,为什么我需要检查字符串是否为字符串?(tryparse方法)如果它是一个数字,很明显它是一个int…对吗??例如,我当前的代码在一个函数中接受年龄,并在主函数中输出它。我尝试将其转换为int,但出现错误cs0019:运算符“==”不能应用于“int”和“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();

C# 我不知道';我不懂c中的字符串# 作为一个只使用C++的人,我很困惑。我看了不同的解释,但似乎还是不明白。例如,为什么我需要检查字符串是否为字符串?(tryparse方法)如果它是一个数字,很明显它是一个int…对吗??例如,我当前的代码在一个函数中接受年龄,并在主函数中输出它。我尝试将其转换为int,但出现错误cs0019:运算符“==”不能应用于“int”和“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();,c#,C#,然后我还得到了错误cs0029:无法将类型“int”隐式转换为“string”(第49行是返回时间),错误cs0029:无法将第58行的类型“string”隐式转换为“int”(int age=GetAge();)int.Parse如果失败,将抛出异常。我会将您的循环修改为: int age; while (!int.TryParse(Console.ReadLine(), out age)) Console.Write("Invalid input. Please try again

然后我还得到了错误cs0029:无法将类型“int”隐式转换为“string”(第49行是返回时间),错误cs0029:无法将第58行的类型“string”隐式转换为“int”(int age=GetAge();)

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()

我不明白你想要什么,为什么。:-)

您不需要检查string是否为string

当输入不是有效整数时,int.Parse将引发异常,但您可以使用TryParse,what is返回布尔值且不引发异常

在C#中,不能比较整数和字符串,必须先将其转换

GetAge方法返回integer,但返回类型声明为string

public static int GetAge()
{
    int age;
    Console.Write("\nPlease input age > ");
    while (!int.TryParse(Console.ReadLine(), out int age))
    {
        Console.Write("Invalid input. Please try again > ");
    };
    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();
}

您正在将变量
age
初始化为整数。因此,它永远不能是字符串,因此不能与字符串进行比较。Age是一个int。您将它与“”进行比较,因此error@Atk如果我试图说,如果没有输入值,那么执行xyz命令,那么这样做是不合理的吗?不,不是。如果没有输入值,代码将在parse方法处中断。必须使用tryparse。
Int32.Parse
Int32.tryparse
不检查字符串是否为字符串。它们将字符串转换为整数,类似于C++的
std::stoi
谢谢!!成功了。你能简单地解释一下吗?我读了网上的解释,他们往往超过我的头。我喜欢写日志解释我的代码,这样我就可以确保我能很好地理解它。@TübaËs sure
int.Parse
如果无法解析参数,将引发异常。只有当我知道解析会成功时,我才会使用它。在任何其他情况下,例如用户输入,都不能保证成功<这里首选code>int.TryParse,因为它不会引发异常,而是返回false。