2012-12-14 48 views
-1

嗨,我想在Visual Studio上編寫一個C#應用程序。我已經創建了一個數組,主要是我試圖訪問一個窗體上的點擊事件,但它告訴我在當前上下文中不存在數組'字符'。我試圖將數組傳遞給窗體,但我仍然有同樣的問題。任何幫助將非常感謝這裏是我的代碼。從主窗口訪問數組

namespace WindowsFormsApplication10 
{ 
    static class Program 
    { 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 

      bool[][] characters = new bool[27][];   // my array characters 

      characters[1][0] = true; 

      Application.Run(new Form1());    
     } 
    } 
} 

namespace WindowsFormsApplication10 
{ 
    public partial class Form1 : Form 
    { 
     int cs1 = 0,cs2=0;  

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public void pictureBox1_Click(object sender, EventArgs e) 
     { 
      if (characters[1][0] == true)  // trying to access member of characters 
      {         // array but characters does not 
               // exist in the current context 
       pictureBox28.Visible = false; 
      } 
     } 
    } 
} 
+1

你有兩個選擇:1,使變量靜態字段'Program',或2.將數組作爲參數傳遞給'Form1'的構造函數。 –

+1

這不是幾乎完全相同的問題嗎? http://stackoverflow.com/questions/13870651/accessing-an-instance-in-main-from-a-form –

回答

0
  1. 存儲您的數組爲靜態申請inobject那麼你可以到處參觀。
  2. 作爲參數傳遞。
  3. RPC
+2

你需要RPC這個簡單的東西? ... –

+0

只需列出所有提案,如果他願意:) –

1

您陣列主要功能的內側限定在僅在其範圍是可見的。

最簡單的你可以做的是將主外移動陣列:

public static bool[][] characters = new bool[27][]; 
static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 

      characters[1][0] = true; 

      Application.Run(new Form1());    


     } 

public void pictureBox1_Click(object sender, EventArgs e) 
     { 

      if (Main.characters[1][0] == true)  // trying to access member of characters 
      {         // array but characters does not 
               // exist in the current context 
       pictureBox28.Visible = false; 
      }    

     } 
0
bool[][] characters = new bool[27][]; 

聲明本地Main方法。因此它在外面看不到。

如果你想內Form1使用它,更改爲以下:

public partial class Form1 : Form 
{ 
    bool[][] characters = null; 
    int cs1 = 0,cs2=0; 

    public Form1(bool[][] characters) 
    { 
     this.characters = characters; 
     InitializeComponent(); 
    } 

    ... 
    ... 
} 

形式Main,請撥打如下:

Application.Run(new Form1(characters));