代码在if语句中不起作用

use*_*728 0 c# if-statement

我在考虑下面一段代码中的if/else语句时遇到了问题.实际上我想告诉我的用户是否找不到文件中的单词我的代码必须显示错误消息,否则我的代码必须显示一个新表单,这是我的代码:

    public void searchGlossary(String word)
    {
        StringBuilder description = new StringBuilder(512);
        string descLine;
        using (StreamReader reader = File.OpenText("C:/Users/--- /Desktop/--- .txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith(word, StringComparison.OrdinalIgnoreCase))
                {
                    // At this point we've already read the keyword and it matches our input

                    // Here we start reading description lines after the keyword.
                    // Because every keyword with description is separated by blank line
                    // we continue reading the file until, the last read line is empty 
                    // (separator between keywords) or its null (eof)
                    while ((descLine = reader.ReadLine()) != string.Empty && descLine != null)
                    {
                        description.AppendLine(descLine);
                    }
                    //descbox.Text = description.ToString();
                    isfound = true;
                    DomainExpertForm form = new DomainExpertForm(keyword, description.ToString());
                    form.Show();
                    break;
                }

            }

            if (isfound == false)
            {
                MessageBox.Show("No Matches found for Word " + word, "Domain Expert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


    }
Run Code Online (Sandbox Code Playgroud)

问题是,如果找不到单词,它总是显示我的表单而不是显示错误消息.有什么问题和解决方案可以帮助我我是新的c#!

Kev*_*ühl 5

你应该声明和初始化isFoundfalse在你的方法的开头:

public void searchGlossary(String word)
{
  var isFound = false; 
  StringBuilder description = new StringBuilder(512);

  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 不仅如此,你应该*在那里声明它.它在更高的范围内宣布是没有意义的. (4认同)