2016-09-29 50 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