繁体   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