开发者

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

开发者 https://www.devze.com 2023-02-24 00:20 出处:网络
I was looking at sample code from MSDN just now and came accross: namespace IListSourceCS { public class Emplo开发者_Python百科yee : BusinessObjectBase

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

namespace IListSourceCS
{
    public class Emplo开发者_Python百科yee : 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 :

  • C# When To Use “This” Keyword
  • When do you use the “this” keyword?
0

精彩评论

暂无评论...
验证码 换一张
取 消