2012-08-01 48 views
-1

哪些代碼塊要寫入以及到達和分配的位置? 嗨,對所有的基本問題抱歉,但我會很高興,如果你可以解釋下面的一些問題。謝謝。哪個代碼塊要寫入以及要在哪裏分配和分配?

namespace forms 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      // in thic code block what kind of things can i write or im allowed to write? Q1 
     } 

     Form2 frm2 = new Form2(); // why should i write this line (since i already added form2 to my project as seen in the picture) ![enter image description here][1]to see frm2.Show(); in button1_Click part? Q2 
     //what happens in the background (from the compiler point of view) when i do Form2 frm2 = new Form2();? Q3 

     frm2.Show(); // why cant i reach frm2 in here? i just declared above. Q4 
     //just like that 
     int number1; // i declare number variable in here 
     number1= 5; // and why cant i assign number in here? 

     // what kind of things can i write or allowed to write in this block ? Q5 
     // i sometimes confuse where i need to start writing the code or where i need to write or in which block ? 

     public int number2; 

     // ok now lets say i put a button on the form and when i double click it generated the code down below 
     //and now lets look in that code block 

     private void button1_Click(object sender, EventArgs e) 
     {  
      // ok now we are in this block and now it see when i write 
      frm2.Show(); 
      //or 
      //it see when i write 
      number1 = 5; 
      //ok now lets look at number1 and number2 what changes when i write public int and just int without public? Q6 
     } 
    } 
} 

enter image description here

+0

第23行的錯誤是什麼? – socksocket 2012-08-01 09:12:33

+0

你可以閱讀上面的代碼和問題。實際上沒有問題,但我這樣做是爲了提出問題並獲得答案,以便我能更多地啓發。 – 2012-08-01 09:16:36

回答

2

首先你的代碼不應該行編譯:

frm2.Show(); 

number1= 5; 

這些線路應該是方法的一部分。

現在你的問題。

Q1。這是Form1類的構造塊。您可以在Form1的第一次執行時執行初始化和其他您想要執行的操作。 Q2302。你行

Form2 frm2 = new Form2(); 

Form2創建一個實例,但您將文件添加到項目中,使用Form2,你必須首先創建它的一個實例。

Q3。上面的行創建了一個實例Form2,調用Form2的構造函數並將Form2的實例分配給其引用frm2

Q4。你不能做frm2.Show();,只有字段定義和初始化可以在課堂上完成。這條線應該是某種方法的一部分。 Q30。

Q5。與Q4相同的答案

編輯: Q6。如果用int指定public,則該字段將在類外部可訪問,並且如果您未指定任何內容,則默認爲internal

+0

因此對於Q1的回答,它就像C++中的Main()funcktion一樣嗎?以及如何爲Q6什麼時候改變我寫公共int和只是int沒有公開? – 2012-08-01 10:06:15

+0

@modestandcutegirl,不是真的,Main是程序中的入口點,來自Constructor請參閱:http://msdn.microsoft.com/en-us/library/ace5hbzh.aspx – Habib 2012-08-01 10:09:33

+0

謝謝,如果你不介意你說Q6的話。提前致謝。 – 2012-08-01 10:22:18