in C# In object -oriented programming, it is usually defined in the base class, and these methods are rewritten or redefined in the derivative class. Although both "Virtual" and "New" keywords can be used to modify the method declaration, they have different implementation methods.
dirtual rewriting
The method declared in the base class as "virtual", indicating that subclasses can be rewritten.
State a new method of the same name as the foundation Chinese method in the derivative class.
Hide the basic method and create a new implementation in the derived class.Public Class Base {{ public virtual bool dosomething () {Return false;} } Public class derived: base: base {{ Public override bool dosomething () {Return True;} }
If we create a Derived instance and store it in the base type variable, the call for Dosomething () will call the method of rewriting in Derived:
public class Base
{
public virtual bool DoSomething() { return false; }
}
public class Derived : Base
{
public override bool DoSomething() { return true; }
}
On the contrary, if we use the new keyword in Derived, the call for dosomething () will call a new method in Derived. Even if the variable is Base type:
Base a = new Derived();
a.DoSomething(); // 返回 true
base a = new derived (); a.dosomething (); // Return to True (new method in derived)
public class Derived : Base
{
public new bool DoSomething() { return true; }
}
Base a = new Derived();
a.DoSomething(); // 返回 true (Derived 中的新方法)
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3