【问题标题】:Why is a string working in MessageBox but not in the if statement为什么字符串在 MessageBox 中有效但在 if 语句中无效
【发布时间】:2019-11-29 20:02:39
【问题描述】:
            WebClient wc = new WebClient();
            string code = wc.DownloadString("link");
            MessageBox.Show(code); // CODE SHOWS IN MESSAGEBOX CORRECTLY.
            if (textbox.Text == code)
            {
                MessageBox.Show("Key Approved!");
                try
                {
                    Form1 Form1 = new Form1();
                    Form1.Show();
                    this.Hide();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("This Key is incorrect.");
            }

文本框内的文本是代码字符串中的文本,虽然textbox.Text == code 为假,它返回到else 参数。

知道为什么会这样吗?

【问题讨论】:

  • 返回的字符串中可能有前导或尾随空格。
  • 我查过了,没有。
  • 我们可能需要查看您正在比较的字符串样本。还有可能包含零长度字符。您应该检查要比较的两个字符串的长度是否相同。其他可能性可能是看起来相同但实际上是不同字符的同形文字。
  • 因为textbox.Textcode 不是同一个字符串。当你在某个地方显示它时,它可能看起来一样,但实际数据不一样。
  • 我建议你create a hex dump对这两个字符串进行比较。

标签: c# winforms textbox messagebox


【解决方案1】:

Textbox 中的文本是代码字符串中的文本,虽然 textbox.Text == code 为 false,它返回到 else 参数。

我不相信你。而且由于你没有为此提供证据,我相信你错了。

这表明TextBox.Textcode 不同。如果它们看起来相同,那么差异可能是额外的空格、大小写或其他细微差别。

唯一可以想象的原因是您以某种方式覆盖了字符串相等运算符以执行意外的操作。

试试这个代码:

Test(TextBox.Text, code);

void Test(string textbox, string code)
{
    if (textbox.Length != code.Length)
    {
        MessageBox.Show("Strings are different lengths!");
        return;
    }

    for (int i = 0; i < textbox.Length; i++)
    {
        if (textbox[i] != code[i])
        {
            MessageBox.Show(string.Format("'{0}' does not equal '{1}'", textbox[i], code[i]));
            return;
        }
    }
    MessageBox.Show("Strings are identical!");
}

【讨论】:

  • @Fabio:这是 明确的答案。现在确认是正确的。
【解决方案2】:

在比较字符串时为什么不使用.equals() 而不是==

【讨论】:

  • 这只在 Java 中有所不同,在 C# 中没有。
猜你喜欢
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多