C# 检查文本框是否包含不起作用的单词
它似乎只检测/检查列表中的第一个单词C# 检查文本框是否包含不起作用的单词,c#,list,foreach,textbox,contains,C#,List,Foreach,Textbox,Contains,它似乎只检测/检查列表中的第一个单词 private bool ContentCheck() { List<string> FilteredWords = new List<string>() { "duck", "donkey", "horse", "goat", "dog", "cat"
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);
}
}
private bool ContentCheck()
{
List FilteredWords=新列表()
{
“鸭子”,
“驴子”,
“马”,
“山羊”,
“狗”,
“cat”,//经过审查的单词列表
“狮子”,
“老虎”,
“熊”,
“鳄鱼”,
“鳗鱼”,
};
foreach(FilteredWords中的变量e)
{
if(memoEdit1.Text.Contains(e))
{
返回true;
}
其他的
{
返回false;
}
}
返回false;
}
私有无效按钮\u单击(对象发送者,事件参数e)
{
if(ContentCheck()==false)
{
//做点什么
}
else if(ContentCheck()==true)
{
MessageBox.Show(“错误:冒犯性的词。”,“错误”,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
在foreach
块中的if
语句中,这两种情况都会导致返回。考虑一下,程序将迭代列表中的第一项,如果是脏话,它将返回,如果不是,它也将返回。这两项都将退出代码,因此下一项将永远不会被迭代
要解决此问题,您需要更改
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;