2013-02-13 78 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

相关问题