base() and this() constructors best practices

后端 未结 5 1734
予麋鹿
予麋鹿 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:30

    Use base when there is inheritance, and a parent class already provides the functionality that you're trying to achieve.

    Use this when you want to reference the current entity (or self), use it in the constructor's header/signature when you don't want to duplicate functionality that is already defined in another constructor.

    Basically, using base and this in a constructor's header is to keep your code DRY, making it more maintainable and less verbose

    Here's an absolutely meaningless example, but I think it illustrates the idea of showing how the two can be used.

    class Person
    {
        public Person(string name)
        {
            Debug.WriteLine("My name is " + name);
        }
    }
    
    class Employee : Person
    {
        public Employee(string name, string job)
            : base(name)
        {
            Debug.WriteLine("I " + job + " for money.");
        }
    
        public Employee() : this("Jeff", "write code")
        {
            Debug.WriteLine("I like cake.");
        }
    }
    

    Usage:

    var foo = new Person("ANaimi");
    // output:
    //  My name is ANaimi
    
    var bar = new Employee("ANaimi", "cook food");
    // output:
    //  My name is ANaimi
    //  I cook food for money.
    
    var baz = new Employee();
    // output:
    //  My name is Jeff
    //  I write code for money.
    //  I like cake.
    

提交回复
热议问题