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>
( instance) calls Foo
, it returns B
because the Bar
in clB
directly. B
Foo
Rewriting 1
B
Foo
In contrast, the rewriting requires
Example:
In the previous example, the method of override
, 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!