c#字符串迭代器,用于一一显示单词 [英] c# string iterator for showing words one by one

查看:19
本文介绍了c#字符串迭代器,用于一一显示单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What I want to do is a program that includes textbox (or something else that allows me to do it ) and this textbox is going to show the text from my resource .txt file and this is going to be like one word after another or two words after another for users to improve eye-movement on the text. To make it more clear the textbox is going to show the words two by two . I can do it by using string array but it only works on Listbox and Listbox is not okay for this project because it goes vertical and I need horizontal text like as we see in books.

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

And this is the code that shows the logic of what ı want but ı cannot use it it stops when I click the button.

{
    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,这通常是不受欢迎的,但这是我知道如何使按钮处理程序异步的唯一方法.

Here's how to do it with async and await. It uses async void, which is generally frowned upon, but it's the only way I know how to make a button handler async.

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

I don't fish the starting string out of resources, I just do this:

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

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

And, I carved of the retrieval and splitting of the string it's own function (that uses yield return to fabricate the enumerator).

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

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

Then all that's left is the code that sticks the words in the text box. This code does what I think you want (puts the first word in the text box, pauses slightly, puts the next, pauses, etc.).

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

这篇关于c#字符串迭代器,用于一一显示单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆