构造函数链接的目的? [英] Purpose of Constructor chaining?

查看:96
本文介绍了构造函数链接的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读此构造函数链接问题我很想知道为什么要有人构造函数链接?

After reading this Constructor chaining question I am just curious to know why would any one do constructor chaining?

有人可以说明一些可能有用的方案类型.

Could some one please shed some light on type of scenarios where this might be useful.

这是一种好的编程习惯吗?

Is this a good programming practice?

推荐答案

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

It's absolutely a good practice for two main reasons:

为避免代码重复

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

强制执行良好的封装

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

这篇关于构造函数链接的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆