开发者

Generic static fields initialization

I'm j开发者_Python百科ust getting curious about the following code :

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

As I've understood the static class Container will be initialized when the following code executes:

...
var emptyArray = Container<int>.EmptyArray;
...

Am I right ? Any explanations on static generic classes/members initialization would be appreciated. Thanks in advance.


The guarantee is that the static field is initialized before you access it. (And also, if there is also a static constructor, then all static fields will be initialized before the static constructor is run.)

For generic classes, static initialization works on a per-type basis, so Container<int> acts as if it is a completely different class to Container<double>. This is actually true for all static parts of a generic class - each type gets its own 'copy'.

An example will show this last point more clearly:

static class Foo<T>
{
    static int count = 0;
    public static int Increment()
    {
        return ++count;
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Foo<int>.Increment());
        Console.WriteLine(Foo<int>.Increment());
        Console.WriteLine(Foo<double>.Increment());
    }
}

Output:

1
2
1


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<T>
{
    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<string> and Container<bool> are not the same, the static constructor is called once for each type of T.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜