c#字符串迭代器,用于一一显示单词

问题描述

我想要做的是一个包含文本框(或其他允许我这样做的东西)的程序,这个文本框将显示我的资源 .txt 文件中的文本,这就像一个词之后一两个字一个一个地让用户提高对文字的眼球运动。为了更清楚,文本框将两个两个地显示单词。我可以通过使用字符串数组来实现,但它只适用于 ListBox,而 ListBox 不适用于这个项目,因为它是垂直的,我需要像我们在书中看到的那样的水平文本。

这是显示我想要但我无法使用它的逻辑的代码,当我单击按钮时它会停止。

{
    public Form1()
    {
        InitializeComponent();
    }

    string[] kelimeler;


  

    private void button1_Click(object sender,EventArgs e)
    {
        const char Separator = ' ';
        kelimeler = Resource1.TextFile1.Split(Separator);

    }


    private void button2_Click(object sender,EventArgs e)
    {
        for (int i = 0; i< kelimeler.Length; i++)
        {
            textBox1.Text += kelimeler[i]+" " ;

            Thread.Sleep(200);


        }


        
    }
}

解决方法

以下是如何使用 asyncawait。它使用 async void,这通常是不受欢迎的,但这是我知道如何使按钮处理程序异步的唯一方法。

我不会从资源中提取起始字符串,我只是这样做:

private const string Saying = @"Now is the time for all good men to come to the aid of the party";

而且,我对字符串的检索和拆分进行了雕刻,这是它自己的函数(使用 yield return 来制作枚举器)。

private IEnumerable<string> GetWords()
{
    var words = Saying.Split(' ');
    foreach (var word in words)
    {
        yield return word;
    }
}

那么剩下的就是将文字粘贴在文本框中的代码了。此代码执行我认为您想要的操作(将第一个单词放入文本框中,稍微停顿一下,放置下一个,暂停等)。

private async void button3_Click(object sender,EventArgs e)
{
    textBox4.Text = string.Empty;
    foreach (var word in GetWords())
    {
        textBox4.Text += (word + ' ');
        await Task.Delay(200);
    }
}