【问题标题】:Linked-list and generic type链表和泛型类型
【发布时间】: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


【解决方案1】:
private Node next;  

这行代码应该怎么理解?

nextNode 类型的私有字段

public Node Next                   
{
    get { return next; }
    set { next = value; }
}

我猜这是一个以类名作为类型的属性?

这是一个名为Next的属性,其类型为Node

private Node head;  

为什么嵌套类名出现在应该是 head 类型的地方?
这是GenericList&lt;T&gt; 类的私有字段吗?

因为它是 head 的类型,是的,它是外部类的私有字段。

这里没有什么特别的,一个类可以有与自己相同类型的字段、属性等

编辑关于评论“它如何通过创建一个嵌套类类型 Node 的字段来使代码工作?(...) plus field 'next ' 在创建 Node 实例时定义为 null"

所有的“魔力”都在于 AddHead 方法。
当您首先创建实例 GenericList(比如 GenericList)时,head 为 null
所以在这一步之后,我们可以说列表可以表示为 []

然后你调用 AddHead(1) 例如;它创建一个具有该值的节点,然后将其设置为当前头的旁边,最后将新创建的节点设为新头。
所以在这一步之后,列表是:1 -> [](一个带有 1 的头,它链接到它的下一个节点;空节点又名空列表)

之后,如果您再次调用 AddHead 并说 2 ;你会以这样的结尾:2 -> 1 -> []

当需要迭代时,您只需在头部不为空(也称为 null)时循环,读取它的存储值并使用链接节点(它是下一个)作为“新头部”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    相关资源
    最近更新 更多