如何使用C#通过Winforms中的类从数组获取值

我有一个名为Game.cs的类,在该类中,我有以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simon
{
    class Game
    {
        public int[] TheArray = new int[1000];

        private bool m_Play;
        public bool Play
        {
            set { m_Play = value; }
            get { return m_Play; }
        }

        public Game()
        {
            Random rnd = new Random();

            for (int i = 0; i < 8; i++)
            {
                TheArray[i] = rnd.Next(0, 4); // between 0 and 3
            }

        }


    }
}

我希望能够从表单中调用TheArray.我希望循环能够根据我单击button5的时间进行迭代,然后我想根据数组返回的内容以编程方式单击我的按钮.在我的表单上,我有4个按钮,分别为button1,button2,button3和button4.

单击button5后,我的代码每次在遍历TheArray时都需要单击基于数组的按钮

到目前为止,我有这个:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Simon
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Game m_game;

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("box1");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("box2");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("box3");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            MessageBox.Show("box4");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            // Determine which button to click based on TheArray
        }

    }
}

解决方法:

要单击基于数组的按钮(我假设数组中的0对应于button1,依此类推,您可以尝试如下操作:

private void button5_Click(object sender, EventArgs e)
{
     Button[] button = { button1, button2, button3, button4 };
     for (int i = 0; i < m_game.TheArray.Length; i++)
     {
         button[m_game.TheArray[i]].PerformClick();
     }
}

附带说明一下,正如@ThunderGr在评论中指出的那样,您必须创建游戏实例或将其静态化.

上一篇:C#-如何在值更改(而不失去焦点)时验证numericupdown


下一篇:c#-更改下拉菜单列表项为正方形