泛型程式碼中的預設關鍵字 (C# 程式設計手冊)
在泛型類別和方法中會發生一個問題,也就是當您無法預先知道下列資訊時,如何將預設值指派給參數化型別 T:
T 是參考型別或實值型別
如果 T 是實值型別,則會是數字值或結構
當指定參數化型別 T 的變數 t 時,只有在 T 是參考型別時,陳述式 t = null 才有效,並且 t = 0 只有對數值型別 (而不是結構) 有效。 解決方法是使用 default 關鍵字,對參考型別傳回 null 而對數值型別傳回零。 這種方法會根據結構是實值或參考型別,為結構傳回初始化成零或 null 的每個結構成員。 對於可為 Null 的實質型別,預設值會傳回 System.Nullable<T>,該值會與任一結構一樣經過初始化。
下列 GenericList<T> 類別的程式碼範例示範如何使用 default 關鍵字。 如需詳細資訊,請參閱泛型概觀。
namespace ConsoleApplication1
{
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;
}
}
}