標籤:
對於泛型類的聲明
其中使用型別參數的構造類型,比如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
我們從最後兩行的輸出也可看出結果
即:不同型別參數的封閉構造類型之間是不共用靜態成員變數的。
C#泛型-小心使用靜態成員變數