我不明白之間的差別簡單的裸何時以及爲什麼要使用ClassName:this(null)?
Public ClassName() {}
和
Public ClassName() : this(null) {}
我知道我可以只使用它,如果我有一個+1
重載的構造函數,但我不明白的這種方式的優點defining the parameterless constructor
。
我不明白之間的差別簡單的裸何時以及爲什麼要使用ClassName:this(null)?
Public ClassName() {}
和
Public ClassName() : this(null) {}
我知道我可以只使用它,如果我有一個+1
重載的構造函數,但我不明白的這種方式的優點defining the parameterless constructor
。
這允許單參數構造函數具有所有邏輯,所以不會重複。
public ClassName() : this(null) {}
public ClassName(string s)
{
// logic (code)
if (s != null) {
// more logic
}
// Even more logic
}
我希望這是明確指出,「邏輯」和「更邏輯」會需要若不是在參數的構造函數重複進行this(null)
。
一個非常有用的情況是像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.
}
}
}
有一種叫做構造器注入的模式。這種模式主要用於單元測試和邏輯分享。這裏是一個例子
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)。並做構造函數中的所有邏輯,其中最多的參數
但在你的情況,空傳遞,所以這是一個基於上下文。我必須知道你的背景是什麼。
構造函數注入與依賴注入一起使用。這個問題和你的答案都是關於構造器鏈接。 – 2013-02-13 19:00:24
請參閱:[C#Constructor Chaining](http://stackoverflow.com/q/1814953/) – 2013-02-13 18:58:20
它清理了一下API,並通過重用隱含的單參數構造函數來減少代碼重複。 – JosephHirn 2013-02-13 19:25:21