C# 泛型类型中的静态变量

C# 泛型类型中的静态变量

ZKEASOFT March 03, 2017


静态变量在程序的开发中经常使用到,最明显的特性就是全局共享值,但是在泛型类型中却不是这样。

原文描述

A static variable in a generic class declaration is shared amongst all instances of the same closed constructed type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply regardless of whether the type of the static variable involves any type parameters or not.

Section 25.1.4 of the ECMA C# Language specification

简单翻译一下意思就是:在泛型的不同类型中,不共享值。

通用类声明中的静态变量在同一封闭构造类型(§26.5.2)的所有实例之间共享,但不在不同封闭构造类型的实例之间共享。 无论静态变量的类型是否涉及任何类型参数,这些规则都适用。

简单测试一下:

class C<V>
{
    static int count = 0;
    public C()
    {
        count++;
    }
    public static int Count
    {
        get { return count; }
    }
}
class Application
{
    static void Main()
    {
        C<int> x1 = new C<int>();
        Console.WriteLine(C<int>.Count);  // Prints 1 
        C<double> x2 = new C<double>();
        Console.WriteLine(C<double>.Count); // Prints 1 
        Console.WriteLine(C<int>.Count);  // Prints 1 
        C<int> x3 = new C<int>();
        Console.WriteLine(C<int>.Count);  // Prints 2 
    }
}

微信公众号