Usage of virtual and new keywords in C#
In object-oriented programming, methods are usually defined in base classes and overridden or redefined in derived classes. Although both the "virtual" and "new" keywords can be used to modify method declarations, they are implemented in different ways.
virtual rewrite
new keyword
Example
Consider the following code:
public class Base { public virtual bool DoSomething() { return false; } } public class Derived : Base { public override bool DoSomething() { return true; } }
If we create an instance of Derived and store it in a variable of type Base, the call to DoSomething() will call the overridden method in Derived:
Base a = new Derived(); a.DoSomething(); // 返回 true
In contrast, if we use the new keyword in Derived, the call to DoSomething() will invoke the new method in Derived, even if the variable is of type Base:
public class Derived : Base { public new bool DoSomething() { return true; } }
Base a = new Derived(); a.DoSomething(); // 返回 true (Derived 中的新方法)
When to use virtual override vs. new
The above is the detailed content of Virtual vs. New in C#: When to Override or Hide Base Class Methods?. For more information, please follow other related articles on the PHP Chinese website!