簡體   English   中英

C# - 擴展方法

[英]C# - Extension method

我筋疲力盡了。 需要幫助字符串類型“words”的正確擴展方法是什么..... words.Text ==“blue”產生錯誤

  string userInput = textBox1.Text;
            string[] words = userInput.Split();
           if (words.Text ==" blue ") 
            {
             string color = words[2];
             label1.Text = "The third word is: " + color;
            }
            else 
            {
                label1.Text = "Not enough words.";
            }

您無法在字符串數組上獲取“.Text”,即“words”。 但是,您可以執行以下操作:

        for (int i = 0; i < words.Length; i++)
        {
            Console.WriteLine(string.Format("The {0} word is {1}", i+1, words[i]));
        }

但是,我不確定您要做什么。

從數組中正確檢索值:

string userInput = textBox1.Text;
string[] words = userInput.Split();

foreach(string word in words)
{
    if(word == "blue")
    {
        string color = word;
        label1.text = "The third word is: " + color;
    }
    else
    {
        label1.Text = "Not enough words.";
    }
}

我不確定你要做什么,但如果我嚴格遵守,你可以這樣做:

if (words[2] ==" blue ") 
{
 string color = words[2];
 label1.Text = "The third word is: " + color;
}
else 
{
    label1.Text = "Not enough words.";
}

如果您指的是 Linq 然后在數組中找到單詞 blue 它可能是

if (words.Any(x=>string.Equals(x, "blue"))) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM