通用静态字段初始化

通用静态字段初始化

本文介绍了通用静态字段初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

正如我已经理解静态类Container将在下面的代码时被初始化执行:

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

我是对吗?赞赏静态泛型类/成员初始化的任何解释。提前致谢。

解决方案

保证是静态字段在您访问它之前被初始化。 (另外,如果还有一个静态构造函数,那么在静态构造函数运行之前,所有静态字段都将被初始化。)对于泛型类,静态初始化可以工作每个类型的基础,所以 Container< int> 就好像它是一个完全不同于 Container< double> 。这对于泛型类的所有静态部分都是如此 - 每种类型都有自己的'复制'。



一个例子会更清楚地显示最后一点:

  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());


$ / code $ / pre
$ b $输出:

  1 
2
1


I'm just 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

这篇关于通用静态字段初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:06