简体   繁体   English

访问 C# 中的私有方法

[英]Access to a private method in C#

Hi People I'm newbie in the C# world and I'm having a problem.大家好,我是 C# 世界的新手,我遇到了问题。 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:我在程序的 Form_Load 方法中做了一个数组,但是我需要像这样在 picture_box 方法中访问数组:

        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 pictureBox1_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但我只得到错误:错误 1 当前上下文中不存在名称“imgArray”

You need to define int[] imgArray at the class level (outside of Form2_Load) rather than inside it.您需要在 class 级别(Form2_Load 外部)而不是内部定义 int[] imgArray。 Otherwise the "scope" of that variable is limited to that function.否则,该变量的“范围”仅限于 function。 You will need to knock off the first "int[]" part in Form2_Load to prevent you from just declaring a new variable.您需要取消 Form2_Load 中的第一个“int[]”部分,以防止您只声明一个新变量。

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.您已经在Form2_Load function的 scope 中声明了数组。 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.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM