Hidden and rewriting in C#: In -depth analysis
In object -oriented programming, the inheritance mechanism is very important in expansion and modification. However, there are two different mechanisms when modifying methods: hiding and rewriting.
Hidden: The method of shielding the foundation
Hidden is a member of the same name as a member who inherited from the base class. Different from rewriting, the derived class will not establish a father -son relationship. Instead, it creates a new entity of hidden foundation members.
The following is an example:
In this scene, the Sayhello () method declared in DOG hides the method inherited from Animal. When the DOG object calls Sayhello (), it will execute the hidden method to block the implementation of the base class.
<code class="language-csharp">class Animal { public virtual string SayHello() { return "Hello from Animal"; } } class Dog : Animal { public new string SayHello() { return "Hello from Dog"; } }</code>
On the other hand, rewriting refers to the same signature method of the sub -classes state inheritance as the parent class inheritance. By default, the rewriting method Inherits the access to the modifier and the return type of the base class method. However, they can modify the realization of customs.
In this example, the Sayhello () method in the DOG rewrite the method defined in Animal. When calling on the DOG object, the method of rewriting is provided to provide custom behaviors specific to the dog.The key difference between hiding and rewriting
<code class="language-csharp">class Animal { public virtual string SayHello() { return "Hello from Animal"; } } class Dog : Animal { public override string SayHello() { return "Hello from Dog"; } }</code>
Access permissions: The access to the base method method of reserving the base class method, and the hidden allowing the derived class to modify it.
Inheritance relationship:The above is the detailed content of Shadowing vs. Overriding in C#: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!