C# 泛型 default()方法
在泛型类和泛型方法中产生的一个问题是,在预先未知以下情况时,如何将默认值分配给参数化类型 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); } }