2016-09-29 36 views
-2

我学习泛型。 Richter LinkedList。我有关于类初始化的问题。 加:有2个构​​造函数。先用null。 我们如何用1个构造函数做到这一点?泛型params里氏代码

internal sealed class Node<T> 
{ 
    public T m_data; 
    public Node<T> m_next; 

    public Node(T data) : this(data, null) 
    { 
    } 

    public Node(T data, Node<T> next) 
    { 
     m_data = data; m_next = next; 
    } 

    public override String ToString() 
    { 
     return m_data.ToString() + ((m_next != null) ? m_next.ToString() : String.Empty); 
    } 
} 

什么是?

public Node(T data) : this(data, null) 
{ 
} 

尤其(T data)

为什么我能做什么?

public Node(T data, Node<T> next) 
     { 
      m_data = data; m_next = null; 
     } 

但我不能做

public Node(T data, Node<T> next) 
     { 
      m_data = null; m_next = next; 
     } 
+1

构造函数接受通用约束'T'的实例。快速举例,类型节点将在构造函数中使用'string'。 – Igor

+1

您的Node类的构造函数需要一个名为'data'类型的参数T –

+0

有2个构造函数。先用null。我们如何用1个构造函数做到这一点? – ifooi

回答

1

如何,我们可以用1个一个构造办呢?

您可以在构造

internal sealed class Node<T> { 
    public T m_data; 
    public Node<T> m_next; 

    public Node(T data, Node<T> next = null) { 
     m_data = data; 
     m_next = next; 
    } 

    public override String ToString() { 
     return m_data.ToString() + ((m_next != null) ? m_next.ToString() : String.Empty); 
    } 
} 

这将允许像

var node1 = new Node<string>("hello world"); //the same as (data, null) 
var node2 = new Node<string>("how are you", node1); 

什么是public Node(T data) : this(data, null)用法使用可选参数?

它被称为构造函数链/重载。

看看C# constructor chaining? (How to do it?)

1

这是从一个LinkedList剪断一个例子。

T是您的类型的占位符。所以如果你使用Node<int>你设置的类型是一个整数 - 这是通用的。 data是构造函数中的变量名称。

Node<int> foo = new Node<int>(1); 的用法是一样的List<int> foo = new List<int>();这可能是你熟悉的

有2构造函数。先用null。我们如何用1个 构造函数做到这一点?

您可以删除一个,如果它不needet或设置默认值这样的更换两节:

public Node(T data, Node<T> next = null) 
{ 
    m_data = data; m_next = next; 
} 
+0

有2个构造函数。先用null。我们如何用1个构造函数做到这一点? – ifooi

+1

@ifooi更新了我的答案。如果你对LinkedList感兴趣,我最近已经实现了一个http://codereview.stackexchange.com/questions/138142/linked-list-in-c – fubo