开发者

C# static constructor ordering [closed]

开发者 https://www.devze.com 2023-04-01 14:04 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
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

精彩评论

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