Generic static fields initialization

前端 未结 2 746
我在风中等你
我在风中等你 2021-01-18 20:53

I\'m just getting curious about the following code :

public static class Container
{
    public static readonly T[] EmptyArray = new T[0];
}
         


        
2条回答
  •  萌比男神i
    2021-01-18 21:35

    Static field initializers are really moved into the static constructor (type initializer) of the class. So your code compiles into this automagically:

    public static class Container
    {
        public static readonly T[] EmptyArray;
    
        static Container()
        {
            EmptyArray = new T[];
        }
    }
    

    From MSDN about static constructors:

    It [Static Constructor] is called automatically before the first instance is created or any static members are referenced.

    Since Container and Container are not the same, the static constructor is called once for each type of T.

提交回复
热议问题