在泛型類和泛型方法中產生的一個問題是,在預先未知以下情況時,如何將默認值分配給參數化類型 T:
-
T 是引用類型還是值類型。
-
如果 T 為值類型,則它是數值還是結構。
給定參數化類型 T 的一個變量 t,只有當 T 為引用類型時,語句 t = null 才有效;只有當 T 為數值類型而不是結構時,語句 t = 0 才能正常使用。解決方案是使用 default 關鍵字,此關鍵字對於引用類型會返回 null,對於數值類型會返回零。對於結構,此關鍵字將返回初始化為零或 null 的每個結構成員,具體取決於這些結構是值類型還是引用類型。對於可以為 null 的值類型,默認返回 System.Nullable<T>,它像任何結構一樣初始化。
class Program { static void Main(string[] args) { // Test with a non-empty list of integers. GenericList<int> gll = new GenericList<int>(); gll.AddNode(5); gll.AddNode(4); gll.AddNode(3); int intVal = gll.GetLast(); // The following line displays 5. System.Console.WriteLine(intVal); // Test with an empty list of integers. GenericList<int> gll2 = new GenericList<int>(); intVal = gll2.GetLast(); // The following line displays 0. System.Console.WriteLine(intVal); // Test with a non-empty list of strings. GenericList<string> gll3 = new GenericList<string>(); gll3.AddNode("five"); gll3.AddNode("four"); string sVal = gll3.GetLast(); // The following line displays five. System.Console.WriteLine(sVal); // Test with an empty list of strings. GenericList<string> gll4 = new GenericList<string>(); sVal = gll4.GetLast(); // The following line displays a blank line. System.Console.WriteLine(sVal); } } // T is the type of data stored in a particular instance of GenericList. public class GenericList<T> { private class Node { // Each node has a reference to the next node in the list. public Node Next; // Each node holds a value of type T. public T Data; } // The list is initially empty. private Node head = null; // Add a node at the beginning of the list with t as its data value. public void AddNode(T t) { Node newNode = new Node(); newNode.Next = head; newNode.Data = t; head = newNode; } // The following method returns the data value stored in the last node in // the list. If the list is empty, the default value for type T is // returned. public T GetLast() { // The value of temp is returned as the value of the method. // The following declaration initializes temp to the appropriate // default value for type T. The default value is returned if the // list is empty. T temp = default(T); Node current = head; while (current != null) { temp = current.Data; current = current.Next; } return temp; } }
關於 default(t)
///之所以會用到default關鍵字, ///是因為需要在不知道類型參數為值類型還是引用類型的情況下,為對象實例賦初值。 ///考慮以下代碼: class TestDefault<T> { public T foo() { T t = null; //??? return t; } } ///如果我們用int型來綁定泛型參數,那么T就是int型, ///那么注釋的那一行就變成了 int t = null;顯然這是無意義的。 ///為了解決這一問題,引入了default關鍵字: class TestDefault<T> { public T foo() { return default(T); } }