3

私はC#プログラミングが初めてです。私を助けてください。

クラスを作成しましたTester

class Tester 
{
    public int a = 5;
    public int b = a;
}

a質問 1: 変数の初期化にこの変数を使用できないのはなぜですかb

質問 2: 変数を静的に変更すると、正常に動作します。なぜ違いがあるのですか?

class Tester
{
    public static int a = 5;
    public static int b = a;
}

質問 3: 前の例で、変数のシーケンスを入れ替えると正常に動作abます。どのように初期化できますaか?

class Tester
{
    public static int b = a; // 0
    public static int a = 5; // 5
}
4

3 に答える 3

1

アニルーダが言ったように。インスタンス変数を使用して別のインスタンス変数を初期化することはできません。なんで?コンパイラはこれらを再配置できるため、a前に初期化されるという保証はありませんb

これにはコンストラクターを使用できます。

class Tester
{
   public int a=5;
   public int b;
   public Tester()//constructor
   {
      b=a;
   }
}

また

class Tester
{
    public static int a = 5;
    public static int b;
    public Tester()//constructor
    {
        b = a;
    }
}
于 2013-10-14T10:08:24.620 に答える