【问题标题】:C# changing a string to Int or having it as an int [duplicate]C# 将字符串更改为 Int 或将其作为 int [重复]
【发布时间】:2015-08-12 16:57:51
【问题描述】:

您好,我正在尝试将信息添加到 int 中,但我不知道如何将其声明为 Int

我正在尝试以 int 形式输入年龄,但不知道如何输入。

我的代码:

        Author authorAdd = new Author();
        authorAdd.Name = txtName.Text;
        authorAdd.Age = txtAge.Text;

我试过 .Int 我知道我需要的不是 .Text,但我不记得我需要什么了,谢谢。

【问题讨论】:

  • int.Parse Convert.ToInt32
  • 另外,int.TryParse(避免异常)

标签: c# string int


【解决方案1】:

这样试试

authorAdd.Age = int.Parse(txtAge.Text);

如果年龄可以为空

那就这样试试

int age;

if(int.TryParse(txtAge.Text,out age)){
  authorAdd.Age = age;
}

【讨论】:

    【解决方案2】:

    尝试以下方法:

    authorAdd.Age = int.Parse(txtAge.Text);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2023-01-10
      • 2012-07-26
      • 2018-02-07
      • 2013-09-01
      相关资源
      最近更新 更多