繁体   English   中英

C#TextBox.Text =多个单词

[英]C# TextBox.Text = Multiple words

是否有可能制造出比一个单词更多的单词,我创建了一个计时器,该计时器检查文本框中键入的内容,如果键入的写密码更改了图片,那么我的其他if函数不起作用,我该如何做类似的事情这个:

语句的代码,我需要这样的代码: if (metroTextBox1.Text == "byby", "cow", "root")

if (metroTextBox1.Text == "byby")
{
     Image img = Properties.Resources.Good_Pincode_48px; // Right'as
     metroTextBox1.Icon = img;
}
else
{
    // new wrong().Show();
    Image img = Properties.Resources.Wrong_Pincode_48px; // Wrong'as
    metroTextBox1.Icon = img;
}

尝试这个:

if(new string[] { "byby", "cow", "root" }.Contains(metroTextBox1.Text))
{
   ...
}

编辑:

就像注释中建议的那样,您可以使用HashSet而不是Array来存储要比较的单词。 Contains方法与HashSet一起使用的速度更快,因为它具有O(1)查找,而ArraysLists具有O(n)查找。

HashSet<string> words = new HashSet<string>(){ "byby", "cow", "root" };
if (words.Contains(metroTextBox1.Text))
{
    ...
}

好吧,我将2美分加到SlavenTojić的回答中:

  • 您可以创建一个包含单词集合的属性:

     private HashSet<string> WordsList { get; } = new HashSet<string>(new[] { "byby", "cow", "root" }); 

  • 并将事件处理程序添加到TextBox TextChanged事件中:

     this.textBox1.TextChanged += TextBox1OnTextChanged; 

  • 在事件处理程序中,使用collection检查其是否包含元素:

     private void TextBox1OnTextChanged(object sender, EventArgs e) { if (this.WordsList.Contains(textBox1.Text)) { // ... } } 

与比较器配合使用以避免出现大小写问题

      if(new string[] { "byby", "cow", "root" }
         .Contains(metroTextBox1.Text,StringComparison.OrdinalIgnoreCase))
        {
           ...
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM