开发者

Access to a private method in C#

Hi People I'm newbie in the C# world and I'm having a problem. I have done an array in the Form_Load method of my program, but I need to access the array in a picture_box method like this:

        private void Form2_Load(object sender, EventArgs e)
    {
        //In this method we get a random array to set the images

        int[] imgArray = new int[20];

        Random aleatorio = new Random();

        int num, contador = 0;

        num = aleatorio.Next(1, 21);

        imgArray[contador] = num;
        contador++;

        while (contador < 20)
        {
            num = aleatorio.Next(1, 21);
            for (int i = 0; i <= contador; i++)
            {
                if (num == imgArray[i])
                {
                    i = contador;
                }
                else
                {
                    if (i + 1 == contador)
                    {
                        imgArray[contador] = num;
                        contador++;
                        i = contador;
                    }
                }
            }
        }

    }


    private void pictur开发者_如何学CeBox1_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = Image.FromFile(@"C:\Users\UserName\Desktop\MyMemoryGame\" + imgArray[0] + ".jpg");
    }

But I only get the error: Error 1 The name 'imgArray' does not exist in the current context


You need to define int[] imgArray at the class level (outside of Form2_Load) rather than inside it. Otherwise the "scope" of that variable is limited to that function. You will need to knock off the first "int[]" part in Form2_Load to prevent you from just declaring a new variable.

For example:

public class MyClass
{ 
    private int[] myInt;

    public void Form2_Load(...) {
        myInt = ...;
    }

}


The error means exactly what it says.

You've declared the array in the scope of the Form2_Load function. Outside of it, it will not exist.

To do what you're trying to achieve, add a private array to the form itself.

private int[] _imgArray = new int[20];

private void Form2_Load(object sender, EventArgs e)
{
    //Setup the imgArray
}

private void pictureBox1_Click(object sender, EventArgs e)
{
    //_imgArray is now available as its scope is to the class, not just the Form2_Load method

}

Hopefully that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜