C#方法重載(overload)、重寫(覆蓋)(override)、隱藏(new)


重載

同一個作用域內發生(比如一個類里面),定義一系列同名方法,但是方法的參數列表不同。這樣才能通過傳遞不同的參數來決定到底調用哪一個。而返回值類型不同是不能構成重載的。

作用:  重載必須發生在一個類中,函數名相同,參數類型或者個數可以不同,返回值類型可以不同。根據參數選擇調用方法。重載就是讓類以統一的方式處理不同的數據,在同一個類中多個方法可以用同一個名字就叫做方法重載。

 

 

 

重寫override

作用:用於實現接口、抽象類、虛方法

重寫override一般用於接口實現和繼承類的方法改寫,要注意:

  1、覆蓋的方法的標志必須要和被覆蓋的方法的標志完全匹配,才能達到覆蓋的效果;

 

  2、從 C# 9.0 開始,override 方法支持協變返回類型。 具體而言,override 方法的返回類型可從相應基方法的返回類型派生。 在 C# 8.0 和更早版本中,override 方法和重寫基方法的返回類型必須相同。

    3、不能重寫非虛方法或靜態方法。 重寫基方法必須是 virtualabstractoverride

  4、覆蓋的方法所拋出的異常必須和被覆蓋方法的所拋出的異常一致,或者是其子類;

 

  5、被覆蓋的方法不能為private,否則在其子類中只是新定義了一個方法,並沒有對其進行覆蓋。

重寫object 類型的ToString()

 

  6、可以說,override是一個非常智能的東西,它可以動態決定究竟是采用父類還是子類的方法。

 

   public override string ToString() { return base.ToString(); }

 

 

 

隱藏(new)

隱藏簡單地說就是基類中已經定義的方法,派生類中也需要用,而兩個方法完全相同的話就會出現語法錯誤,所以用關鍵字new把基類中的方法隱藏了,但是該方法想用的時候還可以發揮作用,又不會發生語法沖突。

 

using System;  
using System.Text;  
  
namespace OverrideAndNew  
{  
    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  
        }  
    }  
  
    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");  
        }  
    }  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM