Introduction to this keyword of C basic knowledge

  • 2021-09-24 23:23:57
  • OfStack

1. this can represent the current instance of the reference class, including inherited methods, and can usually be omitted.


public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(string Name, int Age)
    {
        this.Age = Age;
        this.Name = Name;
    }
}

Needless to say, when an object calls its own internal function, it can use this for the object.

2. The this keyword is followed by the ":" symbol, and other constructors can be called


// Declare an implemented constructor
public Person()
{
    this.NAge = 100;
    Console.WriteLine(" I'm Superman! ");
}
public Person(int nAge)
{
    Console.WriteLine(" Superman's Age {0}", nAge);
}
 // Use this Keyword calls the first 2 A 1 Constructor of 1 parameter
public Person(int nAge, string strName)
    : this(1)
{
    Console.WriteLine(" I'm called {0} Superman, age {1}", strName, nAge);
}

Let's create the object to see if the call was successful. Add the following code to the Main function:

Person p = new Person(10," Hadron ");

Execution outputs:


Superman's Age 1
I'm a superman named Hadron, age 10

3. Declare an indexer

The indexer type indicates which type 1 index the indexer uses to access an array or collection element, which can be an integer or a string; this stands for an array or collection member that manipulates this object and can simply be understood as the name of the indexer, so the indexer cannot have a user-defined name. For example:


public class Person
{
    string[] PersonList = new string[10];
    public string this[int param]
    {
        get { return PersonList[param]; }
        set { PersonList[param] = value; }
    }
}

Where the data type of the index must be the same as the index type of the indexer. For example:


Person person = new Person();
person[0] = "hello";
person[1] = "world";
Console.WriteLine(person[0]);

It looks like an array of 1 objects, hehe.


Related articles: