如何循环遍历数组并逐个显示其元素 [英] How to loop through an array and display its elements one by one

查看:381
本文介绍了如何循环遍历数组并逐个显示其元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,请说如下3个元素:

Hi, I have an array, let say 3 elements in it as below:

string [] message = {how, are, you};
int counterTimerValue = 0;





对于数组中的每个元素,我需要显示它们10秒钟。当它到达最后一个元素时,它将返回第一个元素并一次又一次显示第一个元素,第二个元素。

我使用了一个计时器对象来控制持续时间,但对如何我应该为每个元素分配一个计时器左右。

以下是我目前的代码:





For each element in the array, I would need to display them for 10 seconds for example. And when it reach the final element, it will go back to the first element and display the first element, second element again and again.
I have used a timer object to control the duration but clueless on how should I assign each element a timer or so.
Below are my current codes:

for(int i = 0; i < message.Length; i++)
{
    //txtNotification.Text = "";
    //txtNotification.Text = "Notification:";

    counterTimerValue = 10;
    displayTimer.Interval = 1000; // 1 second
    displayTimer.Tick += new EventHandler(this.displayTimerTick);
    displayTimer.Start();

    //txtNotification.Text = txtNotification.Text + message[i];
}










private void displayTimerTick(Object source, EventArgs e)
{
     counterTimerValue--;
     try
     {
         int index = (messageArray.Length - 1 - (counterTimerValue % messageArray.Length));
         txtNotification.Text = messageArray[index];
     }
     catch (Exception)
     {
     }
     if (counterTimerValue == 0)
     {
        displayTimer.Stop();
     }
}







以上代码只显示最后一个元素你,因为for循环将完成执行数组中的所有元素,而不是等待计时器完成一个元素,然后只去另一个元素。

任何帮助将不胜感激。谢谢。



我的尝试:



1.搜索任何想法/头脑风暴但无济于事。




The above codes will only display the last element "you" because the for loop will finish executing all the elements in the array instead of wait for the timer to finish one element then only go for another element.
Any help would be appreciated. Thank you.

What I have tried:

1. Search online for any ideas/brainstorming but no avail.

推荐答案

您必须将显示数组项的代码移动到计时器处理程序中。类似

You have to move the code that displays the array item into the timer handler. Something like
private void displayTimerTick(Object source, EventArgs e)
{
    counterTimerValue--;
    try
    {
       int index = (message.length - 1 - (counterTimerValue % message.length));
       txtNotification.Text = message[index];
    }
    catch (Exception)
    {
    }

    if (counterTimerValue == 0)
    {
       displayTimer.Stop();
    }
}


这篇关于如何循环遍历数组并逐个显示其元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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