【问题标题】:Operator '==' cannot be applied to operands of type 'string' and 'int' [closed]运算符'=='不能应用于'string'和'int'类型的操作数[关闭]
【发布时间】:2014-10-25 14:16:36
【问题描述】:
private void button1_Click(object sender, EventArgs e)
{
    Random random = new Random();
    int getal1 = random.Next(0, 100);

    Random random2 = new Random();
    int getal2 = random2.Next(0, 100);
    int Antwoord = getal1 + getal2;

    if (Antwoord == textBox1.Text);
        ...
}

它说

运算符“==”不能应用于“字符串”和“整数”类型的操作数

有人可以帮我吗?

【问题讨论】:

  • 您需要学习 C# 的基础知识。即使是简单的教程,答案也会很清楚。
  • Antwoord 是一个整数,而 textBox1.Text 是一个字符串。因此,您无法比较它们。您必须先将textBox1.Text 转换为整数(反之亦然将Antwoord 转换为字符串)。

标签: c#


【解决方案1】:
if (Antwoord.ToString() == textBox1.Text);

这样写。你想检查 int 到字符串,这是不可能的。您应该将 int 值转换为字符串或将字符串值转换为 int。我建议您将 int 转换为 string,否则可能会出现异常。

【讨论】:

    【解决方案2】:

    如果你需要一个整数值,在TextBox中输入,你应该尝试解析它的Text

    int textBox1Value;
    if (int.TryParse(textBox1.Text, out textBox1Value))
    {
        // Here the text was successfully parsed to the textBox1Value variable
        if (Antwoord == textBox1Value)
        {
           ... // do your stuff
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 2017-09-21
      • 2017-01-19
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多