-1

どのコード ブロックを記述し、どこに到達して割り当てるか? こんにちは、基本的な質問で申し訳ありませんが、以下のQを説明していただければ幸いです. ありがとう。

 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
        } 
    }
}

ここに画像の説明を入力

4

2 に答える 2

2

まず、コードをオンラインでコンパイルしないでください。

frm2.Show();

number1= 5;

これらの行は、メソッドの一部である必要があります。

今あなたの質問に。

Q1. Form1それがクラスのコンストラクターブロックです。の最初の実行時に実行したい初期化やその他のことを行うことができますForm1

Q2. あなたのライン

Form2 frm2 = new Form2();

のインスタンスを作成してForm2います。ファイルをプロジェクトに追加しますが、使用Form2するには、最初にそのインスタンスを作成する必要があります。

Q3. 上記の行は のインスタンスを作成し、Form2のコンストラクターを呼び出し、のインスタンスをその参照Form2に割り当てています。Form2frm2

Q4. frm2.Show();クラスレベルでできるのは、フィールドの定義と初期化だけです。この行は、何らかのメソッドの一部である必要があります。

Q5. Q4と同じ答え

編集:Q6。int で指定するpublicと、そのフィールドはクラス外からアクセス可能になり、何も指定しない場合はinternalデフォルトでアクセス可能になります。

于 2012-08-01T09:18:31.680 に答える
2

Visual C# Programming - How to Programなどの優れた C# Ebook を入手することをお勧めします。

あなたが尋ねる質問は、C#のコンストラクターオブジェクト変数クラスのアクセシビリティでカバーされています。また、多数の無料の c# 書籍がオンラインで公開されています

于 2012-08-01T09:39:13.873 に答える