문제

I have the following scenario:

Class A
{
    public static  A instance;

    static A()
    {
        if(condition)
        {
            instance = new B();
        }
        else
        {
            instance = new A();
        }

    }

    public A()
    {
        WriteSomething();
    }

    virtual void WriteSomething()
    {
        Console.WriteLine("A constructor called");
    }

}


Class B : A
{
    public B()
    {
        WriteSomething();
    }

    override void WriteSomething()
    {
        Console.WriteLine("B constructor called");
    }

}

The problem is that when A.instance is called the first time and if condition is true and the B() constructor is called, for some reasons I do not undestand the output of the program is "A constructor called".

Can you please help with an explanation!

Thank you!

도움이 되었습니까?

해결책

The constructor for A will always run first, even if you are creating a new B, since B extends A.

You have also inadvertently discovered why it's recommended that you don't put virtual function calls in a constructor (at least in .NET).

http://msdn.microsoft.com/en-us/library/ms182331.aspx

"When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed."

다른 팁

A.WriteSomething() will always give you "A constructor called" B.WriteSomething() will always give you will always give you "A constructor called". However in a constructor scenario, override is not being called, you can use new keyword to make new voids with the same name. This works the way you want besides a virtual override call. However, the code above is not a good implementation.

Class A
{
    public static  A instance;

    static A()
    {
        if(condition)
        {
            instance = new B();
        }
        else
        {
            instance = new A();
        }

    }

    public A()
    {
        WriteSomething();
    }

    public static void WriteSomething()
    {
        Console.WriteLine("A constructor called");
    }

}


Class B : A
{
    public B()
    {
        WriteSomething();
    }

    public static new void WriteSomething()
    {
        Console.WriteLine("B constructor called");
    }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top