在迭代foreach循环时递增计数器

时间:2013-12-01 19:57:33

标签: c#-4.0

我需要在每次调用ShowNote()方法后增加k,以便每个音符按顺序显示。我试图放置k ++但不知何故它不起作用。 我已经放置了一个文本框来查看k的值是否实际上是递增但是它总是相同的,因此图像彼此放置而不是按顺序放置。

我该如何解决这个问题...

  private void panel1_Click(object sender, EventArgs e)
    {
        int[] xLoc = {0,70,140,210,280,350,420};
        int k = 0;
        int yLoc = 50;
        foreach (MusKey mk in this.panel2.Controls)
        {
            if (sender == mk)
            {

                textBox1.Text = "Key No. " + mk.musicNote.ToString() + " pressed";
                MusicNote musNote = new MusicNote(mk.musicNote,"Crotchet.bmp");
                musNote.PlaySound();
                this.panel3.Controls.Add(musNote);
                musNote.ShowNote("", xLoc[k], yLoc); 
                k++;
                textBox2.Text = Convert.ToString(k); //Done for testing.. too see if k      is incrementing....
                musNote.BringToFront();
            } 
        } 
    }

1 个答案:

答案 0 :(得分:0)

   private int[] xLoc = {0,70,140,210,280,350,420};
   private int k = 0;

 private void panel1_Click(object sender, EventArgs e)
    {

        int yLoc = 50;
        foreach (MusKey mk in this.panel2.Controls)
        {
            if (sender == mk)
            {

                textBox1.Text = "Key No. " + mk.musicNote.ToString() + " pressed";
                MusicNote musNote = new MusicNote(mk.musicNote,"Crotchet.bmp");
                musNote.PlaySound();
                this.panel3.Controls.Add(musNote);
                musNote.ShowNote("", xLoc[k], yLoc); 
                k=k>=xLoc.Length-1? xLoc.Length:k++; // so that k does not point to non existent location
                textBox2.Text = Convert.ToString(k); //Done for testing.. too see if k      is incrementing....
                musNote.BringToFront();
            } 
        } 
    }