构造函数链的目的是什么?

San*_*eep 6 c# java oop constructor coding-style

在阅读了这个构造函数链接问题之后,我只是想知道为什么会有人进行构造函数链接?

有人可以对这可能有用的场景类型有所了解.

这是一个很好的编程习惯吗?

Jos*_*osh 5

这绝对是一个好习惯,主要有两个原因:

避免代码重复

class Foo
{
    public Foo(String myString, Int32 myInt){
        //Some Initialization stuff here
    }

    //Default value for myInt
    public Foo(String myString) : this(myString, 42){}

    //Default value for both
    public Foo() : this("The Answer", 42){}
}
Run Code Online (Sandbox Code Playgroud)

强制执行良好的封装

public abstract class Foo
{
    protected Foo(String someString)
    {
        //Important Stuff Here
    }
}

public class Bar : Foo
{
    public Bar(String someString, Int32 myInt): base(someString)
    {
        //Let's the base class do it's thing
        // while extending behavior
    }
}
Run Code Online (Sandbox Code Playgroud)