Home > Backend Development > C++ > Overriding vs. Shadowing in C#: When Should You Use Each Technique?

Overriding vs. Shadowing in C#: When Should You Use Each Technique?

Linda Hamilton
Release: 2025-01-28 13:56:09
Original
894 people have browsed it

Overriding vs. Shadowing in C#: When Should You Use Each Technique?

The method in the method in the c#rewriting and hiding

In terms of inheritance, C# provides two different technologies to redefine the method in the base class: rewriting and hiding. These two technologies have fundamental differences in terms of working methods and influence on the inheritance chain.

Hidden

Hidden allows you to create a new method of the same name as the foundation Chinese method, but keywords are not used. This method has become a local member of the derived class, hiding the foundation method. When a derived instance calls the hidden method, it will directly execute the implementation of this class, regardless of the inheritance level structure.

Example: override

In this example, the method is hidden in the class

, and the method
<code class="language-csharp">class A
{
   public int Foo(){ return 5;}
   public virtual int Bar(){return 5;}
}
class B : A
{
   public new int Foo() { return 1;}     //隐藏
   public override int Bar() {return 1;} //重写
}</code>
Copy after login
is rewritten. When

( instance) calls Foo, it returns B because the Bar in clB directly. B Foo Rewriting 1 B Foo In contrast, the rewriting requires

keywords. It allows you to define the new implementation of virtual methods in the base class. When the derived instance calls the rewriting method, it will be implemented in the derived class according to the inheritance chain.

Example:

In the previous example, the method of override

is rewritten. When calls , it returns

, because in is rewriting.

The difference between hidden and rewriting B Bar clB The choice between hidden and rewriting depends on your specific needs: Bar 1 B Hidden: Bar When you want to hide the method of inheritance of the base class and use local implementation, use hidden.

Reworching: When you want to redefine the inheritance method and execute the implementation of the derived class, use the rewriting.

The above is the detailed content of Overriding vs. Shadowing in C#: When Should You Use Each Technique?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template