简体   繁体   中英

What is the function of the "this" keyword in a constructor?

I was looking at sample code from MSDN just now and came accross:

namespace IListSourceCS
{
    public class Employee : BusinessObjectBase
    {
        private string      _id;
        private string      _name;
        private Decimal     parkingId;

        public Employee() : this(string.Empty, 0) {} // <<--- WHAT IS THIS???
        public Employee(string name) : this(name, 0) {}

It calls the other constructor in that class with that signature. Its a way of implementing the constructor in terms of other constructors. base can also be used to call the base class constructor. You have to have a constructor of the signature that matches this for it to work.

this lets you call another constructor of Employee (current) class with (string, int) parameters.

This is a technique to initialize an object known as Constructor Chaining

This sample might help some of the different derivations... The first obviously has two constructor methods when an instance is created... such as

FirstClass oTest1 = new FirstClass(); or FirstClass oTest1b = new FirstClass(2345);

The SECOND class is derived from FirstClass. notice it too has multiple constructors, but one is of two parameters... The two-parameter signature makes a call to the "this()" constructor (of the second class)... Which in-turn calls the BASE CLASS (FirstClass) constructor with the integer parameter...

So, when creating classes derived from others, you can refer to its OWN class constructor method, OR its base class... Similarly in code if you OVERRIDE a method, you can do something IN ADDITION to the BASE() method...

Yes, more than you may have been interested in, but maybe this clarification can help others too...

   public class FirstClass
   {
      int SomeValue;

      public FirstClass()
      { }

      public FirstClass( int SomeDefaultValue )
      {
         SomeValue = SomeDefaultValue;
      }
   }


   public class SecondClass : FirstClass
   {
      int AnotherValue;
      string Test;

      public SecondClass() : base( 123 )
      {  Test = "testing"; }

      public SecondClass( int ParmValue1, int ParmValue2 ) : this()
      {
         AnotherValue = ParmValue2;
      }
   }

A constructor is a special method/function that is ran to initialize the object created based on the class. This is where you run initialization things, as setting default values, initializes members in all ways.

" this " is a special word which points so the very own object you're in. See it as the objects refereence within the object itself used to access internal methods and members.

Check out the following links :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM