首页 > 解决方案 > C# - 字符串比较是假的,尽管我检查过

问题描述

我正在使用基本的 Windows 窗体 C#,按钮“Voltar”和单击的代码如下所示。该字符串确实得到了正确的字符串“Voltar”,但是当它到达 if 时,它永远不会进入该代码块。MessageBoxes:它总是在标题中显示带有字符串“b1”的“Outside Voltar”,所以我可以看到它是正确的字符串,但随后直接跳转到“Really past Voltar”。

Button voltar = new Button();
        voltar.Text = " Voltar";
        voltar.Location = new Point(200, 430);
        voltar.Size = new Size(75, 25);
        voltar.Font = new Font("Verdana", 10, FontStyle.Bold);
        voltar.ForeColor = Color.Yellow;
        voltar.BackColor = Color.Red;
        this.Controls.Add(voltar);
        voltar.Click += new EventHandler(submit_click);
    }

    public void submit_click(object sender, EventArgs e)
    {

        Boolean flag = true;

        String b1 = ((Button)sender).Text;
        MessageBox.Show("Outside Voltar", b1, MessageBoxButtons.OK);
        if (b1 == "Voltar")
        {
            MessageBox.Show("Inside Voltar", "Confirm", MessageBoxButtons.OK);
            this.Close();
            app1.Show();
            MessageBox.Show("Past Voltar", "Confirm", MessageBoxButtons.
       }
MessageBox.Show("Really past Voltar", "Confirm", MessageBoxButtons.OK);

标签: c#

解决方案


它的文本中有一个空格:

voltar.Text = " Voltar";
---------------^------------  //here

所以以下行不正确:

if (b1 == "Voltar")

您应该执行以下操作之一:

1- voltar.Text = "Voltar";

2- if (b1 == " Voltar")

3- if (b1.Trim() == "Voltar")


推荐阅读