overriding
When a method occurs in a subclass statement, the method defined in the base class has the same name, return type, and parameter list. Rewriting allows the custom implementation of the base class method. When the sub -class object calls the rewriting method, the code in the subclass will effectively cover the behavior of the base class method. In contrast,
ShadowingWhen a method occurs in a subclass statement, the method of this method has the same name as the method in the base class, but the method signature (return type or parameter list) different. A new method is hidden in the subclass, which replaces the method with the same name in the base class. Call the hidden method on the object of the subclass to perform the code in the subclass, effectively hiding the base method. Consider the following example:
When calling the method on the objects of Class A and B, the expected output is as follows:
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; } // 重写 }
The key difference is when converting the B object to an object:
A clA = new A(); B clB = new B(); Console.WriteLine(clA.Foo()); // 输出:5 Console.WriteLine(clA.Bar()); // 输出:5 Console.WriteLine(clB.Foo()); // 输出:1 Console.WriteLine(clB.Bar()); // 输出:1 // 将 B 转换为 A Console.WriteLine(((A)clB).Foo()); // 输出:5
For hidden methods (FOO), call the realization of the base class.
provides a controlled mechanism to modify the method to implement, while maintaining the inheritance structure.
The above is the detailed content of What's the Difference Between Shadowing and Overriding in C# Inheritance?. For more information, please follow other related articles on the PHP Chinese website!