5

我是 Visual c# 中的一个全新的 n00bie,我遇到了一个让我发疯的奇怪障碍!这是有问题的代码(是的,一个 Hello World 程序):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


            if (textBox1.Text.Equals("Goodbye Cruel World"))
            {
                textBox1.Text = ("Hello World!");

            }
            else { textBox1.Text = ("Goodye Cruel World"); }


        }



    }
}

我也尝试使用 textBox1.Text=="Goodbye Cruel World"; 作为 if 语句的评估参数,在编译器中没有错误(顺便说一下,我使用的是 Visual Studio 2012 Ultimate)

程序运行良好。我将文本框文本属性初始化为“Hello World!” 使用 VS 的设计 GUI。我面临的问题是代码仅在用户第一次单击按钮时才有效。按钮后的任何时间都不会执行任何操作。

我调试了代码,并确保在用户第一次单击按钮时适当地更改了文本框文本属性。当用户第二次单击按钮时(或此后的任何时间),一旦代码到达 if 语句,它就会跳过它,就好像其中表达式的评估是 FALSE。事实上,跟上调试工具的步伐,按钮只会继续执行 else 块中的代码,尽管我知道我正在使用的 TextBox.Text 属性之前已被适当地更改过。

我在这里想念什么???为什么按钮不只是在我硬编码的两个字符串之间切换文本框文本值?

4

3 回答 3

8

您使用的是三个字符串,而不是两个。《再见残酷世界》不等于《再见残酷世界》。因此,您不能指望此源代码中出现任何类型的“字符串交换”行为。

经验教训:不要在代码的不同点使用相同的字符串。相反,创建一个具有该值的常量字符串变量,然后在每次需要时使用它。例如代码见Habib 的回答

于 2013-05-21T10:04:18.843 回答
7

这是在代码中定义字符串常量的情况:

public partial class Form1 : Form
{
    private const string GOODBYE = "Goodbye Cruel World";
    private const string HELLO = "Hello World!";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.Text.Equals(GOODBYE ))
        {
            textBox1.Text = HELLO;

        }
        else { textBox1.Text = (GOODBYE ); }
    }
}

如果您在多个地方使用相同的字符串,那么最好将其定义为 aconst并在代码中的任何地方使用它,这将帮助您减少像现在这样的错误Goodyeis Goodbye,并且也更容易更改/维持。

于 2013-05-21T10:06:33.240 回答
2

检查else 子句中Goodye的拼写。条件将始终为假。

于 2013-05-21T10:06:59.317 回答