如何在C#编程中进行循环?

时间:2013-07-25 03:11:24

标签: c# loops

我必须让20个球在屏幕上移动。我想知道如何使用循环,所以我不必长时间输入代码。目前,我的代码是

for (int i = 0; i < ballSpeedXAxis.Length; i++)
        {
            ballSpeedXAxis[i] = 1;
        }

for (int i = 0; i < ballSpeedYAxis.Length; i++)
        {
            ballSpeedYAxis[i] = 1;
        } 

private void OnUpdate(object sender, object e)
{
Canvas.SetLeft(this.ball1, this.ballSpeedXAxis[1] + Canvas.GetLeft(this.ball1));
Canvas.SetTop(this.ball1, this.ballSpeedYAxis[1] + Canvas.GetTop(this.ball1));
Canvas.SetLeft(this.ball2, this.ballSpeedXAxis[2] + Canvas.GetLeft(this.ball2));
Canvas.SetTop(this.ball2, this.ballSpeedXAxis[2] + Canvas.GetTop(this.ball2));
...
Canvas.SetLeft(this.ball20, this.ballSpeedXAxis[20] + Canvas.GetLeft(this.ball20));
Canvas.SetTop(this.ball20, this.ballSpeedXAxis[20] + Canvas.GetTop(this.ball20));
}

ball1,ball2 ... ball3是图像名称。

1 个答案:

答案 0 :(得分:4)

有各种不同的方式......最显而易见的是:

Image ball1;
Image ball2;
Image ball3;
// .. etc ...

你也可以将它们放在一个数组中:

Image[] balls = new Image[20];

..跟你的速度一样。然后,您可以将更新方法更改为:

private void OnUpdate(object sender, object e) {
    for (int i = 0; i < balls.Length; i++) {
        Canvas.SetLeft(balls[i], ballSpeedXAxis[i] + Canvas.GetLeft(balls[i]));
        Canvas.SetTop(balls[i], ballSpeedYAxis[i] + Canvas.GetTop(balls[i]));
    }
}

其他包括将已创建的图像放入List<Image> ..但是有点糟糕。