1

我刚开始尝试学习 C#。到目前为止,我已经阅读了大约 50 篇教程,并认为我已经很好地理解了。显然我错了。我一直在阅读 msdn.microsoft.com 的 C# Programmer's Reference,但它似乎不是教程的最佳来源。

我实际上是在尝试完成最简单的任务。试图理解变量、操作和输入。我来自网络编程,想将 PHP 脚本变成桌面应用程序,所以我正在尝试学习 C# 的基础知识,我想我可能需要学习另一种语言。

基本上,我有一个文本框和一个按钮。单击按钮时,我想检查文本框中的文本,看看它是否与某个字符串匹配。然后显示一个带有消息的消息框。

private void btnClick_Click(object sender, EventArgs e) {
    if(txtCL.Text == "one") {
        bool myTest = true;
    } else {
        bool myTest = false;
    }
    if(myTest == true) {
        MessageBox.Show("You entered the correct password.", "Important Message");
    } else {
        MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
    }
}

如果有人能给我指点更好的教程,让我学得更快,我将不胜感激。微软的文档真的没有教给我任何东西。

我为这个愚蠢的问题道歉,请随时称我为白痴。

4

4 回答 4

8

这是一个范围界定问题,myTest不存在,至少不存在- 您每次都在每个初始条件的范围内创建它。如果你这样做:

bool myTest = false;
if(txtCL.Text == "one") {
   myTest = true;
}
if(myTest == true) {
    MessageBox.Show("You entered the correct password.", "Important Message");
} else {
    MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}

然后,您指定布尔值,并将其设置为 false(实际上这是 a 的默认值bool),然后检查您的条件是否满足并相应地重新分配它;然后可以对其进行评估以显示您的消息框。

您可以进一步缩短此代码,作为读者的练习。(:

于 2013-03-27T19:31:30.897 回答
3

你真的不需要一个 bool 变量,你可以让它更简单:

private void btnClick_Click(object sender, EventArgs e)
{
    if(txtCL.Text == "one")
    {
        MessageBox.Show("You entered the correct password.", "Important Message");
    }
    else
    {
        MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
    }
}

如果你需要一些教程,只需谷歌“C#初学者教程”,或者如果你喜欢视频教程,你可以看看这里

于 2013-03-27T19:31:16.883 回答
0
    if(...) {
        bool myTest = true;
    } else {
        bool myTest = false;
    }

    // At this point in time 'myTest' is not a known variable. 
    // It's out of scope already s your next line will cause a compile error.
    if(myTest == true) { 
        ...
    }

所以你需要在范围内声明变量

    bool myTest = false;

    if(...) {
        myTest = true;
    } 

    // Now you can use the myTest variable
    if(myTest) { 
        ...
    }

正如您已经指出的那样,您根本不需要该变量,因为这将完全一样

private void btnClick_Click(object sender, EventArgs e) {
    if(txtCL.Text == "one") {
        MessageBox.Show("You entered the correct password.", "Important Message");
    } else {
        MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
    }
}

您可以阅读任意数量的书籍,但由于您已经有 PHP 编程经验,我建议您多实践 C# 方面的经验。同时,一本书当然不会受到伤害。但我认为你所遵循的方法(在线阅读、编码)最终会得到回报。给它一些时间。实践。很多。

于 2013-03-27T19:37:39.110 回答
-2

我假设当您单击按钮时什么都没有发生。这是真的?如果是,请在该行设置一个断点: if(txtCL.Text == "one") ,运行应用程序并单击它。如果您没有达到断点,则“点击”事件和您的代码之间没有联系。探索按钮属性,您将看到一种建立链接的方法。

坚持下去,我以前是 PHP 人,现在是 C# 人。可以办到。

于 2013-03-27T19:30:28.327 回答