10.2.2 Calling the overridden or hidden base class method
You can access the base class members inside of a derived class, whether you are overriding a member or hiding a member. This can be useful in a number of situations, such as:
To hide an inherited public member from a user of a derived class, you can still access its functionality in the class.
To add implementation code to an inherited virtual member, instead of simply replacing it with the newly rewritten execution code.
To do this, you can use the base keyword, which represents the implementation code for the base class contained in the derived class (when you control the constructor, its usage is similar, as described in 9th), for example:
public class MyBaseClass {
public virtual void DoSomething() {
// Base implementation.
}
}
public class MyDerivedClass : MyBaseClass {
public override void DoSomething() {
// Derived class implementation, extends base class implementation.
base.DoSomething();
// More derived class implementation.
}
}
This code executes the dosomething () version contained in MyBaseClass , MyBaseClass is the base class for Myderivedclass, and DoSomething () The version is included in the Myderivedclass. because base uses an object instance, using it in a static member produces an error .
This keyword
In addition to using the Base keyword in chapter 9th, you can also use the This keyword. Like base, this can also be used inside a class member, and the keyword also references an object instance. Just this refers to the current object instance (that is, you cannot use the This keyword in a static member, because a static member is not part of an object instance ).
The most common function of the This keyword is to pass a reference to the current object instance to a method , as shown in the following example:
public void doSomething() {
MyTargetClass myObj = new MyTargetClass();
myObj.DoSomethingWith( this );
}
Where the instantiated Mytargetclass instance has a Dosomethingwith () method with a parameter whose type is compatible with the class that contains the method described above. This parameter type can be the type of the class, the class type inherited by the class, or an interface implemented by this class or System.Object.
Another common use of the This keyword is to qualify members of a local type, for example:
public class MyClass { private int someData; public int SomeData { get { return this.someData;
}
}
}
Many developers like this syntax, which can be used for any member type, since it is possible to see a reference to a member instead of a local variable .
(original) C # learning Note 10--Other topics that define class members 02--class members 02--call an overridden or hidden base class method