Why are field initializers of a derived class are executed before base classes's initializers

后端 未结 4 1389
逝去的感伤
逝去的感伤 2021-01-05 22:03

constructors are executed in the order from top to bottom I.E. base\'s first followed by derived one. This arangement is based on an important OOP assurance that an object (

4条回答
  •  情话喂你
    2021-01-05 22:51

    Field initialisers are executed in the constructor, and as the constructor in the base class is called first, all field initialisers are also executed before the derived constructor executes.

    Example:

    public class Base {
    
      // field initialiser:
      private string _firstName = "Arthur";
    
      public string FirstName { get { return _firstName;}}
      public string LastName { get; private set; }
    
      // initialiser in base constructor:    
      public Base() {
        LastName = "Dent";
      }
    
    }
    
    public class Derived : Base {
    
      public string FirstNameCopy { get; private set; }
      public string LastNameCopy { get; private set; }
    
      public Derived() {
        // get values from base class:
        FirstNameCopy = FirstName;
        LastNameCopy = LastName;
      }
    
    }
    

    Test:

    Derived x = new Derived();
    Console.WriteLine(x.FirstNameCopy);
    Console.WriteLine(x.LastNameCopy);
    

    Output:

    Arthur
    Dent
    

提交回复
热议问题