2012-02-08 134 views
0

如果有多个构造函数,调用其中一个构造函数的优点是什么? 谢谢由其他调用构造函数

+3

那么,从另一个调用一个*方法的优点是什么?构造函数只是*方法*,它们在生成'new'运算符的结果之前被调用。 – 2012-02-08 16:05:43

回答

6

相同的优点,当你做方法重载:如果您想通过默认值基本构造你不要重复相同的代码

public class Person 
{ 
    public Person(string name,string lastName) 
    { 
     Name = name; 
     LastName = lastName; 
    } 

    public Person(string name, string lastName,string address):this(name,lastName) 
    { 
     //you don't need to set again Name and Last Name 
     //as you can call the other constructor that does the job 
     Address = Address; 
    } 
    public string Name { get; set; } 
    public string LastName { get; set; } 
    public string Address { get; set; } 
} 
8

你不重复自己。

实现一个构造函数的改变也会立即影响所有其他的构造函数。 复制和粘贴代码不好,应该避免。你

+0

相关:http://stackoverflow.com/questions/2490884/why-is-copy-and-paste-of-code-dangerous/2490897#2490897 – Oded 2012-02-08 15:52:03

1

public class YourClass 
{ 
    private int SomeInt; 

    public YourClass() : this(0) 
    { 
     // other possible logic 
    } 

    public YourClass(int SomeNumber) 
    { 
     SomeInt = SomeNumber; 
    } 
} 

这遵循了DRY原则(不要重复自己)。一个简单的例子,但它应该说明这个想法。

1

我使用它时,我想将默认值或空值传递给其他构造函数。在上面的情况下,用户在调用构造函数时不必传递null - 他们可以不用任何东西来调用它。

public class Widget(){ 

    public Widget() : this(null){ 

    } 

    public Widget(IRepository rep){ 
     this.repository = rep; 
    } 
} 
3

纵观已经发布的答案我只是将它们与您总是走的方式,从默认的构造函数下降到最专业的构造函数。试图做同样的其他方式总是导致代码复制或问题:

的好办法:

public class Foo() 
{ 
    public Foo() 
     : this(String.Empty) 
    { } 

    public Foo(string lastName) 
     : this(lastName, String.Empty) 
    { } 

    public Foo(string lastName, string firstName) 
     : this(lastName, firstName, 0) 
    { } 

    public Foo(string lastName, string firstName, int age) 
    { 
     LastName = lastName; 
     FirstName = firstName; 
     Age = age; 
     _SomeInternalState = new InternalState(); 
    } 
} 

糟糕的方法:

public class Foo() 
{ 
    public Foo(string lastName, string firstName, int age) 
     : this(lastName, firstName) 
    { 
     Age = age; 
    } 

    public Foo(string lastName, string firstName) 
     : this(lastName) 
    { 
     FirstName = firstName; 
    } 

    public Foo(string lastName) 
     : this() 
    { 
     LastName = lastName; 
    } 

    public Foo() 
    { 
     _SomeInternalState = new InternalState(); 
    } 
} 

的问题第二个例子是该部分如何处理所有的参数现在已经混淆了所有的构造函数,而只是实现了一个(最专业的)。试想一下,你喜欢从这个课程中派生出来。在第二个示例中,您必须覆盖所有构造函数。在第一个示例中,您只需重写最专业的构造函数即可完全控制每个构造函数。

+0

我不是这个例子的粉丝。你可能应该以另一种方式级联。从最高的参数#到最低的 – Kyle 2012-02-09 00:08:44

+2

@Kyle:NNNOOOOOOOO。如你所建议的那样做会导致问题。看到我更新的答案。 – Oliver 2012-02-09 08:20:24

+1

优点与重载 – Kyle 2012-02-16 21:43:38