C#泛型-小心使用静态成员变量

时间:2021-05-21 05:23:03
对于泛型类的声明
其中使用类型参数的构造类型,比如List<T>被称为开放构造类型(open constructed type)
而不使用类型参数的构造类型,例如List<int>被称为封闭构造类型(closed constructed type)。
特别要强调的是不同类型参数的封闭构造类型之间是不共享静态成员变量的。

举个例子

using System;

public class List<T>
{   
    public List(T t)
    {
        _value = t;
        _closedCount++;
    }

public T Value
    {
        get { return _value; }
    }

public int ClosedCount
    {
        get { return _closedCount; }
    }

public static int StaticCount
    {
        get { return _closedCount; }
    }

private T _value;
    private static int _closedCount = 0;
}

public class Test
{
    static void Main()
    {
        List<double> list1 = new List<double>(3.14);
        Console.WriteLine("List1 Value: {0} \t Closed Count: {1}", list1.Value, list1.ClosedCount);

List<double> list2 = new List<double>(0.618);
        Console.WriteLine("List2 Value: {0} \t Closed Count: {1}", list2.Value, list2.ClosedCount);

List<string> list3 = new List<string>("divino");
        Console.WriteLine("List3 Value: {0} \t Closed Count: {1}", list3.Value, list3.ClosedCount);

Console.WriteLine();

Console.WriteLine("List<double> Count: {0}", List<double>.StaticCount);
        Console.WriteLine("List<string> Count: {0}", List<string>.StaticCount);
    }
}

输出结果:
List1 Value: 3.14         Closed Count: 1
List2 Value: 0.618        Closed Count: 2
List3 Value: divino       Closed Count: 1

List<double> Count: 2
List<string> Count: 1

其中:
list1与list2同为List<double>,它们之间共用静态成员_closedCount
而类型为List<string>的list3不能使用_closedCount
我们从最后两行的输出也可看出结果
即:不同类型参数的封闭构造类型之间是不共享静态成员变量的。