コード実行後にコンストラクタベースを呼び出す 質問する

コード実行後にコンストラクタベースを呼び出す 質問する

クラス A とクラス B があるとします。クラス B はクラス A を拡張します。(クラス B : クラス A)

ここで、ClassB をインスタンス化するたびに、ランダム コードを実行し、その後でのみ「base」を呼び出して ClassA コンストラクターに到達するとします。

のように:

class ClassA
{
    public ClassA()
    {
        Console.WriteLine("Initialization");
    }  
}

class ClassB : ClassA
{
    public ClassB() //: base() 
    {
        // Using :base() as commented above, I would execute ClassA ctor before                                                         //          Console.WriteLine as it is below this line... 
        Console.WriteLine("Before new");
        //base() //Calls ClassA constructor using inheritance
        //Run some more Codes here...
    }
}

super()私が普段使用しているプログラミング言語では、単に ;の後に呼び出すだけでそれができますConsole.WriteLine()が、C# ではそれができません。他の構文や方法はありますか?

ベストアンサー1

インスタンス変数初期化子を使用してこれを行うハッキーな方法があります:

using System;

class ClassA
{
    public ClassA()
    {
        Console.WriteLine("Initialization");
    }  
}

class ClassB : ClassA
{
    private readonly int ignoreMe = BeforeBaseConstructorCall();

    public ClassB()
    {
    }

    private static int BeforeBaseConstructorCall()
    {
        Console.WriteLine("Before new");
        return 0; // We really don't care
    }
}

class Test
{
    static void Main()
    {
        new ClassB();
    }    
}

少ないハッキーな方法としては、ClassBまず の構築方法を再考することです。クライアントがコンストラクターを直接呼び出すのではなく、クライアントが呼び出す静的メソッドを提供します。

public static ClassB CreateInstance()
{
    Console.WriteLine("Before initialization stuff");
    return new ClassB();
}

おすすめ記事