In -depth understanding of the method in c# rewriting
In object -oriented programming, the method rewriting allows the derivative class to provide its own implementation of the method of inheritance of the base class. C# offers two very different methods of rewriting: "Virtual" and "Override" keywords, or simply declare a new method with the same signature.
Virtual Override
When the method is declared "Virtual" in the base class, it can be rewritten in the derived class using the "override" keyword. This method allows derivatives to provide its own implementation while maintaining the original method signature. When running, when the object is derived type, even if the reference variable holding the object is a base type, the rewriting method will be called.
New
Or, you can re -write the new method by declared a new method with the same signature and marked it as "NEW". This method completely replaces the implementation of the base class, and no matter what the type of the object is running, the rewriting method will be called.
Differential examples
In order to explain the difference, please consider the following code fragment:
If we call the code as follows:
public class Foo
{
public virtual bool DoSomething() { return false; }
}
public class Bar : Foo
{
public override bool DoSomething() { return true; }
}
Copy after login
The result will be different according to the method for rewriting:
Foo a = new Bar();
a.DoSomething();
Copy after login
Virtual Override: The method of recurring in the derived class (BAR) when runtime, even if the object is stored in the FOO type variable. -
New: New methods in the derived class (BAR) will be used to effectively replace the implementation of the base class (FOO).
-
Main differences
In short, the main difference between "Virtual", "Override" and "NEW" is:
Calling:
Virtual Override only allows calling and rewriting methods when the type of object is matched with the derivative class, and new methods are always called, regardless of the type of the object.
Implementation:
Virtual Override maintain the original method signature and allow the derived class to provide alternative implementation, and New replace the implementation of the base class. -
Uses: Virtual Override is more suitable for polymorphism. Different derived classes provide their own implementation, and New is suitable for modifying or customized base methods.
-
The above is the detailed content of C# Method Overriding: Virtual/Override vs. New – What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!