c# override,new關鍵字區別與使用(學習筆記)

來源:互聯網
上載者:User

今天看到一個朋友
在override,new上的問題搞錯,呵呵我想很多剛入門的朋友也一樣吧
我呢就查查資料順便鞏固一下自己的理解,現在整理出學習筆記.

先看段代碼:

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4
 5namespace ConsoleApplication1
 6{
 7    class Program
 8    {
 9
10        static void Main(string[] args)
11        {
12            baseClass bc;
13            class1 ct1 = new class1();
14
15            class2 ct2 = new class2();
16
17            ct1.prinf();
18            bc = ct1;
19            bc.prinf();
20
21            Console.WriteLine("---------------------");
22            
23            ct2.prinf();
24            bc = ct2;
25            bc.prinf();
26
27        }
28    }
29
30    public class baseClass
31    {
32        private int index = 0;
33
34        public virtual void prinf()
35        {
36
37            Console.WriteLine("這是基類虛方法" + index.ToString());
38
39        }
40
41    }
42
43    public class class1 : baseClass
44    {
45        private int index = 1;
46
47        public override void prinf()
48        {
49
50            Console.WriteLine("這是子類新的方法" + index.ToString());
51
52        }
53
54    }
55
56    public class class2 : baseClass
57    {
58        private int index = 2;
59
60        public new void prinf()
61        {
62
63            Console.WriteLine("這是子類新的方法" + index.ToString());
64
65        }
66
67    }
68
69
70}
71


運行結果:
這是子類新的方法1
這是子類新的方法1
---------------------
這是子類新的方法2
這是基類虛方法0

如上
使用override重寫printf方法,通過父類引用一樣只能看到重寫後的方法;
如果使用new隱藏printf方法,父類子類引用各自對應方法;

override重寫虛方法,那麼就只剩下重寫以後的方法;
new隱藏基類的方法,那麼基類的方法和當前類的方法同時存在只是被隱藏了;

真想弄些實際應用的例子,想好了補上.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.