c#中重寫(覆蓋)和隱藏類的方法

來源:互聯網
上載者:User

重寫是指重寫基類的方法,在基類中的方法必須有修飾符virtual,而在子類的方法中必須指明override
格式:
基類中:
public virtual void myMethod()
 {
 }
子類中:
public override void myMethod()
 {
 }
重寫以後,用基類對象和子類對象訪問myMethod()方法,結果都是訪問在子類中重新定義的方法,基類的方法相當於被覆蓋掉了。如下例子:

 1using System;
 2class a
 3{
 4    int x=1;
 5    public virtual void PrintFields()
 6    {
 7        Console.WriteLine("x={0}",x);
 8    }
 9}
10
11class b:a
12{
13    int y=2;
14    public  override void PrintFields()
15    {
16        Console.WriteLine("y={0}",y);
17        
18    }
19    
20}
21
22class c
23{
24    public static void Main()
25    {
26        b me=new b();
27        me.PrintFields();
28        a y=new b();
29        y.PrintFields();
30    }
31}

以上代碼運行結果:
y=2
y=2

如果把上面代碼中的override去掉會怎麼樣呢?
那麼啟動並執行時候是不會有錯誤,但是會有個警告,因為編譯器不知道你是要重寫該方法,還是隱藏該方法。如果重寫那麼就加override,如果是隱藏那麼就加new,其實不加new也可以運行,但是我們一般還是加上去。
如果是加了new,那麼運行結果是:
y=2
x=1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.