检查文本框是否包含不起作用的单词

时间:2018-03-31 02:18:56

标签: c# list foreach textbox contains

它似乎只能检测/检查列表中的第一个单词。

private bool ContentCheck()
    {
        List<string> FilteredWords = new List<string>()
        {
            "duck",
            "donkey",
            "horse",
            "goat",
            "dog",
            "cat",                  //list of censored words
            "lion",
            "tiger",
            "bear",
            "crocodile",
            "eel",
        };
        foreach (var e in FilteredWords)
        {
            if (memoEdit1.Text.Contains(e))
            {
                return true; 
            }
            else
            {
                return false;
            }
        }
        return false;
    }

 private void button_click (object sender, EventArgs e)

  {

   if (ContentCheck() == false)
   {
                    //do something
   }

   else if (ContentCheck() == true)
   {
     MessageBox.Show("Error: Offensive word.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
 }

1 个答案:

答案 0 :(得分:2)

if块内的foreach语句中的两种情况都会产生return。考虑一下,程序将迭代列表中的第一项,如果它是一个它将返回的脏话,如果不是它将也返回。这两个都将退出代码,因此下一个项永远不会被迭代。

要解决此问题,您需要更改

foreach (var e in FilteredWords)
{
    if (memoEdit1.Text.Contains(e))
    {
        return true; 
    }
    else
    {
        return false;
    }
}
return false;

foreach (var e in FilteredWords)
{
    if (memoEdit1.Text.Contains(e))
    {
        return true; 
    }
}
return false;
相关问题