开发者

Why isn't the static constructor of the parent class called when invoking a method on a nested class?

开发者 https://www.devze.com 2022-12-26 10:32 出处:网络
Given the following code, why isn\'t the static constructor of \"Outer\" called after the first line of \"Main\"?

Given the following code, why isn't the static constructor of "Outer" called after the first line of "Main"?

namespace StaticTester
{
    class Program
    {
        static void Main( string[] args )
        {
            Outer.Inner.Go();
            Console.WriteLine();

            Outer.Go();

            Console.ReadLine();
        }
    }

    public static partial class Outer
    {
        static Outer()
        {
            Console.Write( "In Outer's static constructor\n" );
        }

        public static void Go()
        {
            Console.Write( "Outer Go\n" );
        }

        public static class Inner
        开发者_StackOverflow社区{
            static Inner()
            {
                Console.Write( "In Inner's static constructor\n" );
            }

            public static void Go()
            {
                Console.Write( "Inner Go\n" );
            }
        }
    }
}


Your question is answered by section 10.12 of the specification, which states:

The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

• An instance of the class type is created.

• Any of the static members of the class type are referenced.

Since you've done neither of those two things, the ctor is not executed.


In the case of nested classes, if the nested class never refers to the static members of it's outer scope, the compiler (and CLR) are not required to call the static constructor of that outer class.

If you want to force the static constructor to run, just add code to the inner type that performs a read of a field or property of the outer type.

You can read more about the lazy initialization semantics of C# on Jon Skeet's blog - it's quite good. You could also check out his book - C# In Depth, it covers these topics as well ... in depth.


Outer.Inner is just referring to a type, it's not actually invoking anything on "Outer".


A static initializer only gets executed when the containing class is used for the first time.

By calling Outer.Inner, you are not using Outer at all, since Outer.Inner is a different type than Outer. So, the static initializer in Outer will not run.

0

精彩评论

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

关注公众号