为什么字符串在MessageBox中起作用,但在if语句中不起作用

问题描述 投票:0回答:2
            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参数。

知道为什么会这样吗?

c# winforms textbox messagebox
2个回答
0
投票

我想通了,我的文本框的最大长度为15个字符,我的代码不止于此。很抱歉浪费您的时间。


0
投票

[文本框内的文本是代码字符串中的文本,尽管textbox.Text ==代码为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!");
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.