Home >Backend Development >C++ >What's the Difference Between Shadowing and Overriding in C#?
Suppose we have a base "a", including two methods "FOO" and "Bar". The "FOO" method is declared for Public, and the "Bar" method declaration is Public Virtual, allowing the derived class to rewrite its implementation. Now, consider a derivative "B" inherited from "A".
Hidden
For example, in the code fragment provided:
The "NEW" keywords before the
Class "B" Chinese method indicate that the "B" type object is accessed by the "B" type. The "FOO" method is effectively hidden.<code class="language-c#">public new int Foo() { return 1;} //隐藏</code>
Rewriting
On the other hand, when the rewriting occurs in a method of the derivative class, the method is the same as the virtual method or abstraction method in the base class. In this case, the implementation of the derived class has explicitly replaced the implementation of the base class and became the default behavior of the derived instance.
Because the "bar" statement in the base "a" is Virtual, the "Override" keyword allows the class "B" to rewrite it and provide its own behavior.
<code class="language-c#">public override int Bar() {return 1;} //重写</code>Impact
When converting the derived instances into a base class reference, hiding may lead to accidental behavior. In this case, the hidden method in the base class may be called instead of the rewriting method in the derivative class, which may cause errors during runtime.
The above is the detailed content of What's the Difference Between Shadowing and Overriding in C#?. For more information, please follow other related articles on the PHP Chinese website!