Home >Backend Development >C++ >What's the Difference Between 'virtual override' and 'new' Keywords in C# Method Overriding?
In object -oriented programming, the method rewriting allows subclasses to provide its own implementation for the method defined in its parent class. This allows the code to achieve customization and polymorphism. However, the method of "Virtual" and "Override" keyword combination declaration base type, as well as using the "New" keywords in the sub -type, has a slight difference between the two.
When the method declared in the base type is "virtual", it indicates that its subclasses can rewrite this method. Therefore, when subclasses use the "Override" keyword rewriting method, it actually replaces the implementation of the base class.
On the contrary, when the method declared in the subclass is "NEW", it creates a new method of the same name as the foundation Chinese method. The subclass method does not rewrite the base method; it runs independently. Behavioral differences
The main differences between
"Virtual Override" and "NEW" are their impact on their behavior during runtime. Consider the following example:If we use "New" instead of "Override" in , it will cause a different way to hide the foundation method. In this case:
Inheritance and polymorphism
<code class="language-csharp">public class BaseClass { public virtual bool DoSomething() { return false; } } public class DerivedClass : BaseClass { public override bool DoSomething() { return true; } } // ... BaseClass obj = new DerivedClass(); obj.DoSomething(); // 返回 true (重写后的实现)</code>When using "Virtual Override", the subclass method can access and modify the implementation of the parent class. This allows flexible inheritance and polymorphism. Instead, "NEW" completely replaced the base method, which destroyed the inheritance chain.
DerivedClass
Virtual scheduling table (VDT)
<code class="language-csharp">//... DerivedClass obj = new DerivedClass(); obj.DoSomething(); // 返回 false (基类实现)</code>
In C#, the virtual method is stored in the virtual scheduling table (VDT). When calling the virtual method, determine the appropriate implementation according to the type of actual object. This makes polymorphism possible. However, the "NEW" method is not included in VDT, which prevents dynamic method selection. Conclusion
"Virtual Override" allows the rewriting base method to achieve inheritance and polymorphism, and "New" creates an independent method in subclasses. Understanding the difference between these two keywords is essential for effective rewriting methods and flexible designs.
The above is the detailed content of What's the Difference Between 'virtual override' and 'new' Keywords in C# Method Overriding?. For more information, please follow other related articles on the PHP Chinese website!