关于泛型
下边的代码是我查msdn的帮助,里边代码大意知道,但是有些表达方式不懂
1.public class GenericList<T> 表示定义一个类吗? 因为以前定义类直接给一个名称, 这个还加了一个<T>,这种表达方式有些费解。
2.public IEnumerator<T> GetEnumerator() ,返回的是一个Node 类型,可是根据IEnumerator<T> 字面是一个接口,我的理解应该是public Node GetEnumerator()
请解释下
在 AddHead 方法中作为方法参数的类型。在 Node 嵌套类中作为公共方法 GetNext 和 Data 属性的返回类型。在嵌套类中作为私有成员数据的类型。注意,T 可用于 Node 嵌套类。如果使用具体类型实例化 GenericList<T>(例如,作为 GenericList<int>),则所有的 T 都将被替换为 int。// type parameter T in angle bracketspublic class GenericList<T> { // The nested class is also generic on T private class Node { // T used in non-generic constructor public Node(T t) { next = null; data = t; } private Node next; public Node Next { get { return next; } set { next = value; } } // T as private member data type private T data; // T as return type of property public T Data { get { return data; } set { data = value; } } } private Node head; // constructor public GenericList() { head = null; } // T as method parameter type: public void AddHead(T t) { Node n = new Node(t); n.Next = head; head = n; } public IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } }}
[解决办法]
public class GenericList<T> :IEnumerator<T>{}