[英]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)
查找,而Arrays
和Lists
具有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.