我不明白之间的差别简单的裸何时以及为什么要使用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