2013-02-13 77 views
8

我不明白之間的差別簡單的裸何時以及爲什麼要使用ClassName:this(null)?

Public ClassName() {} 

Public ClassName() : this(null) {} 

我知道我可以只使用它,如果我有一個+1重載的構造函數,但我不明白的這種方式的優點defining the parameterless constructor

+1

請參閱:[C#Constructor Chaining](http://stackoverflow.com/q/1814953/) – 2013-02-13 18:58:20

+0

它清理了一下API,並通過重用隱含的單參數構造函數來減少代碼重複。 – JosephHirn 2013-02-13 19:25:21

回答

10

這允許單參數構造函數具有所有邏輯,所以不會重複。

public ClassName() : this(null) {} 

public ClassName(string s) 
{ 
    // logic (code) 
    if (s != null) { 
     // more logic 
    } 
    // Even more logic 
} 

我希望這是明確指出,「邏輯」和「更邏輯」會需要若不是在參數的構造函數重複進行this(null)

+0

謝謝你的回覆。 「完全掌握所有邏輯」的意思是什麼? – Sergio 2013-02-13 18:54:18

+1

@Daedalus假設您需要在構造函數中完成一些設置工作,該工作完全不依賴於參數。而不是複製和粘貼代碼兩次,你可以讓paramtetrless的構造函數調用第二個構造函數,並在那裏進行設置工作。 – 2013-02-13 18:57:19

+1

@Daedalus與其在一個構造函數中重複代碼並對一個參數的存在進行細微更改,不如將所有代碼放在一個構造函數中,讓另一個構造函數調用具有所有代碼和一些默認值的代碼。 – Servy 2013-02-13 18:57:40

3

一個非常有用的情況是像WinForms這樣的情況,其中設計師需要無參構造函數,但是您希望表單需要構造函數。

public partial SomeForm : Form 
{ 
    private SomeForm() : this(null) 
    { 
    } 

    public SomeForm(SomeClass initData) 
    { 
     InitializeComponent(); 

     //Do some work here that does not rely on initData.   

     if(initData != null) 
     { 
      //do somtehing with initData, this section would be skipped over by the winforms designer. 
     } 
    } 
} 
+0

好吧,但如果我省略了這個(null)沒有什麼變化,在我的眼前... 我錯過了什麼? – Sergio 2013-02-13 18:57:20

+0

@達達魯斯沒有什麼,這不是一個好例子。 – Servy 2013-02-13 18:58:08

+2

不,如果你省略'this(null)',設計師永遠不會調用'InitializeComponent()' – 2013-02-13 18:58:09

1

有一種叫做構造器注入的模式。這種模式主要用於單元測試和邏輯分享。這裏是一個例子

public class SomeClass 
{ 
    private ISomeInterface _someInterface; 
    public SomeClass() : this (null){} //here mostly we pass concrete implementation 
    //of the interface like this(new SomeImplementation()) 

    public SomeClass(ISomeInterface someInterface) 
    { 
     _someInterface = someInterface;  
     //Do other logics here 
    } 
} 

正如你在這裏看到的,單元測試通過傳遞假實現很容易。另外,邏輯是共享的(DRY)。並做構造函數中的所有邏輯,其中最多的參數

但在你的情況,空傳遞,所以這是一個基於上下文。我必須知道你的背景是什麼。

+0

構造函數注入與依賴注入一起使用。這個問題和你的答案都是關於構造器鏈接。 – 2013-02-13 19:00:24

相關問題