【发布时间】:2015-06-05 00:09:54
【问题描述】:
我正在学习 C# 泛型类型,我对 MSDN 网站上通用模块中的链表示例感到非常困惑: http://msdn.microsoft.com/en-us/library/0x6a29h6.aspx
我在这里粘贴了代码: 我的困惑是:
private Node next;
我应该如何理解这行代码? 我只能认为它是一个使用类名创建的私有字段?
public Node Next
{
get { return next; }
set { next = value; }
}
我猜这是一个以类名作为类型的属性?
private Node head;
为什么嵌套类名出现在应该是 head 类型的地方?
这是 GenericList<T> 类的私有字段吗?
// type parameter T in angle brackets
public 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;** // How should I
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;
}
}
}
【问题讨论】:
-
这里几乎没有魔法。
private Node next;是一个名为next的私有字段,其数据类型为Node。这与它所说的private int next;完全相同。没有魔法。 -
@JohnSaunders 嘿,约翰我明白你的意思了,但它仍然不能安静地回答我的问题:它如何通过创建一个嵌套类类型 Node 的字段来使代码工作?我的意思是 Node 类不返回任何类型,并且每当创建 Node 实例时,加上字段 'next' 都被定义为 null。
-
@EdwardSun 您的问题似乎真的可以归结为“什么是 C# 中的类”......对于 SO 来说可能有点过于宽泛......“类不返回任何类型”是非常奇怪的陈述,很难提供具体的帮助。
-
有一本关于 C# 编程语言的完整手册。在询问有关语言语法的基本问题之前,您应该先查看它。见C# Programming Guide。详细参考请见C# Reference。
标签: c# generics linked-list msdn