base() and this() constructors best practices

后端 未结 5 1728
予麋鹿
予麋鹿 2020-12-02 05:47

Under what conditions am I supposed to make the :base() and :this() constructor calls following my constructor\'s parentheses (or even in other pl

5条回答
  •  春和景丽
    2020-12-02 06:40

    You use :base() when you want the constructor of the base class to be automatically called as first instruction of your constructor. :this() it's similar, but it call another constructor on the same class.

    In base:() and this(): you can pass as parameters constant values , or expression based on parameters of you constructor.

    It's mandatory to call the base constructor when the base class has no default constructor (one that takes no parameters). I don't know of a case in which :this() is mandatory.

    public class ABaseClass
    {
        public ABaseClass(string s) {}
    }
    
    public class Foo : AChildClass
    {
        public AChildClass(string s) : base(s) {} //base mandatory
        public AChildClass() : base("default value") {}  //base mandatory
        public AChildClass(string s,int i) : base(s+i) {}  //base mandatory
    }
    
    public class AnotherBaseClass
    {
        public ABaseClass(string s) {}
        public ABaseClass():this("default value") {} //call constructor above
    }
    
    public class Foo : AnotherChildClass
    {
        public AnotherChildClass(string s) : base(s) {} //base optional
    
    }
    

提交回复
热议问题