【问题标题】:Redefining variable according to Text Box Error根据文本框错误重新定义变量
【发布时间】:2015-02-24 21:38:45
【问题描述】:

我是编码和 C# 的新手,如果这是一个愚蠢的问题,我很抱歉。

我需要根据文本框(用户输入)重新定义变量,但出现错误

int age;
private void Age_TextChanged(object sender, EventArgs e)
   {
       //saves age in years
       age = Age_TextChanged.int;
   }

“age = Age_TextChanged.int;”行出错在 int 位上

错误如下

需要标识符; 'int' 是关键字

首先,这是什么意思,其次,我该如何解决?

【问题讨论】:

  • 我猜你需要age = int.Parse(Age.Text);
  • 您的文本框中没有名为“int”的此类属性。有一个 Text 属性,您需要使用 Convert.ToInt32 将其转换为整数并将其分配给变量“age”
  • 请使用TryParse,这样比较安全。
  • 而且Age_TextChanged 方法上肯定没有int 属性!

标签: c# forms variables compiler-errors


【解决方案1】:

首先,错误消息试图指出您要求的东西不存在。作为附加信息,它还指出int是关键字,不适合作为变量名。

如果您在文本框中输入了一个数字,并希望在该类型的变量中使用等效整数,则需要使用 Int32.TryParse() 尝试将该 String 转换为 Int32

听从我的建议:更好地命名您的控件和变量。随着你的进步,它会让你的事情变得更容易。我已经调整了我的例子:

Int32 iAge;
private void txtAge_TextChanged(Object sender, EventArgs e)
{
    //Saves age in years...
    if (!Int32.TryParse(txtAge.Text, out iAge))
    {
        MessageBox.Show(String.Format("Conversion of '{0}' to Int32 failed!", txtAge.Text), "Bad Data", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    else
    {
        //it parsed into the Int32, so do something with it...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 2018-12-10
    • 2021-07-31
    • 1970-01-01
    • 2014-10-09
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多