我何时以及为什么要使用ClassName:this(null)?

我无法理解简单裸露之间的区别

Public ClassName() {} 

 Public ClassName() : this(null) {} 

我知道只有当我有+1重载的ctor时我才能使用它,但是我无法理解以这种方式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. } } } 

有一种称为构造函数注入的模式。 此模式主要用于unit testing和共享逻辑。 这是一个例子

 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 } } 

如您所见,通过传递虚假实现,unit testing将很容易。 此外,逻辑是共享的(DRY)。 并执行构造函数中包含最多参数的所有逻辑

但在你的情况下,null传递,所以这是一个基于上下文。 我必须知道你的背景是什么。