C# new 和 orverride 區別
阿新 • • 發佈:2019-01-03
主要還是參考微軟的說明,原文:http://msdn.microsoft.com/zh-cn/library/ms173153.aspx
以下是我的理解:
一、BaseClass(父類、基類):
- orverrideBaseClass 中的方法必須宣告為 virtual,否則會出現編譯錯誤;
- newBaseClass 中的方法宣告或不宣告為 virtual 均可。
二、ChildClass(子類)
- orverrideChildClass 中的方法必須宣告為 orverride,否則會出現編譯錯誤;
- newBaseClass 中的方法宣告或不宣告為 new 均可。
大部分情況下,new 和 orverride 處理邏輯是一致的,即呼叫子類的方法。唯獨在 “多型” 這種情況:
BaseClass item = new DerivedClass();
item 呼叫方法時,如果子類中的方法是用 new 宣告的,會呼叫基類的方法,但如果是 orverride 宣告的,則會呼叫子類的方法,這應該是正確的效果。
微軟的例子很經典:
using System; using System.Text; namespace OverrideAndNew { class BaseClass { public virtual void Method1() { Console.WriteLine("Base - Method1"); } public virtual void Method2() { Console.WriteLine("Base - Method2"); } } class DerivedClass : BaseClass { public override void Method1() { Console.WriteLine("Derived - Method1"); } public new void Method2() { Console.WriteLine("Derived - Method2"); } } class Program { static void Main(string[] args) { BaseClass bc = new BaseClass(); DerivedClass dc = new DerivedClass(); BaseClass bcdc = new DerivedClass(); // The following two calls do what you would expect. They call // the methods that are defined in BaseClass. bc.Method1(); bc.Method2(); // Output: // Base - Method1 // Base - Method2 // The following two calls do what you would expect. They call // the methods that are defined in DerivedClass. dc.Method1(); dc.Method2(); // Output: // Derived - Method1 // Derived - Method2 // The following two calls produce different results, depending // on whether override (Method1) or new (Method2) is used. bcdc.Method1(); bcdc.Method2(); // Output: // Derived - Method1 // Base - Method2 } } }