The difference between override and new in C#

rewrite

A method modified with the keyword virtual is called a virtual method. A method with the same name can be declared with override in a subclass, which is called "overriding". The corresponding method that is not modified with virtual, we call it a real method.
Overriding changes the functionality of the parent class method.
See the demo code below:

public class C1
{
    public virtual string GetName()
    {
        return "叔祥";
    }
}

public class C2 : C1
{
    public override string GetName()
    {
        return "xiangshu";
    }
}

 C1 c1 = new C1();
 Console.WriteLine(c1.GetName());//输出“祥叔”

 C2 c2 = new C2();
 Console.WriteLine(c2.GetName());//输出“xiangshu”

 // focus on here

 C1 c3 = new C2();
 Console.WriteLine(c3.GetName());//输出“xiangshu” 

#endregion

 

Overriding 
the method defined in the subclass with the new keyword with the same name as the superclass is called overriding. 
Overriding does not change the functionality of the parent class method.
See the demo code below:

public class C1
{
    public string GetName()
    {
        return "祥叔";
    }
}

public class C2 : C1
{
    public new string GetName()
    {
        return "xiangshu";
    }
}

C1 c1 = new C1();
Console.WriteLine(c1.GetName());//输出“祥叔”

C2 c2 = new C2();
Console.WriteLine(c2.GetName());//输出“xiangshu”

// Focus on this, compare with the rewriting above

C1 c3 = new C2();
Console.WriteLine(c3.GetName());//Output "Uncle Xiang" 

#endregion

 

Summarize

1: Whether it is rewriting or overwriting, it will not affect the function of the parent class itself (nonsense, sure, unless the code is changed).

2: When a subclass is used to create a parent class, such as C1 c3 = new C2(), overwriting will change the function of the parent class, that is, calling the function of the subclass; while overwriting will not, the function of the parent class will still be called.

3: Both virtual and real methods can be overridden (new), but abstract methods and interfaces cannot.

4: Abstract methods, interfaces, methods marked as virtual can be overridden (override), but real methods cannot.

5: The frequency of rewriting is relatively high to achieve polymorphism; the frequency of overwriting is relatively low, when it is used to inherit classes that could not be modified before.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609921&siteId=291194637
Recommended