2011-06-05 123 views
0

嗨,人们我是新手在C#世界,我有一个问题。我已经做了我的程序在Form_Load方法的数组,但我需要访问阵列中的picture_box方法是这样的:在C中访问私有方法#

 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"); 
    } 

但我只得到了错误:错误1名“imgArray”不存在于当前上下文中

+1

导致错误的线是什么? – trutheality 2011-06-05 06:59:41

回答

4

您需要在类级别(Form2_Load外部)定义int [] imgArray,而不是在其内部。否则,该变量的“范围”仅限于该功能。你需要敲掉Form2_Load中的第一个“int []”部分,以防止你只声明一个新的变量。

例如:

public class MyClass 
{ 
    private int[] myInt; 

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

} 
+0

谢谢你,至少在我的情况下,没有必要声明我的数组是私有的。再次非常感谢! – Andres 2011-06-05 07:15:49

3

的错误意味着正是它说。

您已经在Form2_Load函数的范围中声明了该数组。在它之外,它不会存在。

要做你想达到的目的,向表单本身添加一个私有数组。

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 

} 

希望有帮助。