用于逐个显示单词的 c# 字符串迭代器

c# string iterator for showing words one by one

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

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

{
    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);
    }
}