开发者

C# static constructor ordering [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I开发者_如何学编程 am curious as to the order that static and instance constructors are fired. Could someone help me by letting me know what order the constructors below fire?

And what is the explanation behind this behaviour for the execution order of the static constuctors?

class A
    {
        static A()
        {
            Console.WriteLine("I am in A's Static Constructor");
        }
        A()
        {
            Console.WriteLine("I am in A's Default Constructor");
        }
    }

class B:A
{
    static B()
    {
        Console.WriteLine("I am in B's Static Constructor");
    }
    B()
    {
        Console.WriteLine("I am in B's Default Constructor");
    }
}
class C:B
{
    static C()
    {
        Console.WriteLine("I am in C's Static Constructor");
    }
    C()
    {
        Console.WriteLine("I am in C's Default Constructor");
    }
}

What will be the output of the following statement:

C c = new C();


The order is: C, B, A static ctors. A, B, C, default ctors:

Update: Also see this great blog post (Part1 and Part2) from Eric Lippert on why static class initializers run in the reverse order than ctors.


I am in C's Static Constructor
I am in B's Static Constructor
I am in A's Static Constructor
I am in A's Default Constructor
I am in B's Default Constructor
I am in C's Default Constructor
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜