C#裡面的繼承

來源:互聯網
上載者:User
舉個例子:
有一個基類RectangleEx 1 class RectangleEx
 2   {
 3     private int _x, _y, _w, _h;
 4 
 5     public int x
 6     {
 7       get { return _x; }
 8       set { _x = value; }
 9     }
10     public int y
11     {
12       get { return _y; }
13       set { _y = value; }
14     }
15     public int w
16     {
17       get { return _w; }
18       set { _w = value; }
19     }
20     public int h { get { return _h; } set { _h = value; } }
21 
22     protected Pen _pen;
23 
24     public RectangleEx(int x, int y, int w, int h)
25     {
26       _x = x;
27       _y = y;
28       _w = w;
29       _h = h;
30       _pen = new Pen(Color.Black);
31     }
32 
33     //
34     public virtual void Draw(Graphics g)
35     {
36       g.DrawRectangle(_pen, _x, _y, _w, _h);
37     }
38 
39   }

你可以這樣用: 1       
 2       Graphics g = e.Graphics;
 3       Pen p = new Pen(Color.Blue);
 6 
 7       //use RectangleEx class instance;
 8       RectangleEx rex = new RectangleEx(15, 15, 30, 30 );
 9       rex.Draw(g);
10       .

現在需要畫一個正方形,可以這樣:1   class Square : RectangleEx
2   {
3     public Square(int x, int y, int w)
4       : base(x, y, w, w)
5     {
6     }
7   }

上面的base就是跟c++的初始化列表一樣的用法,C#中調用基類方法時,可以用base關鍵字

使用:1 
2       //use square
3       Square sq = new Square(20, 20, 20);
4       sq.Draw(g);//這裡使用了上面的來自PaintEventArgs e 的Griphics對象

這個時候呢,如果我希望有新的衍生類別,能同時畫2個長方形,需要改造Draw()方法(我有兩種辦法)
第一:我可以,把基類的Draw()方法,變成virtual,然後衍生類別override它;
第二:我還可以,通過使用new關鍵字,隱藏基類中的同名方法。
第二種方法是這樣的: 1   class DblRectangleEx : RectangleEx
 2   {
 3     public DblRectangleEx(int x,int y,int w,int h):base(x,y,w,h){
 4       _pen = new Pen(Color.Red);
 5 
 6     }
 7 
 8     private Pen _rPen = new Pen(Color.SeaGreen);
 9 
10    
11     public new void Draw(Graphics g)//使用new關鍵字,覆蓋基類中的同名方法
12     {
13       g.DrawRectangle(_pen, x, y, w, h);
14       g.DrawRectangle(_rPen, x+5, y+5, w, h);
15     }
16 
17     /*
18     public override void Draw(Graphics g)//如果是相同的方法(參數和傳回值)只能用override(要求基類聲明時用virtual關鍵字)
19     {
20       g.DrawRectangle(_pen, x, y, w, h);
21       g.DrawRectangle(_rPen, x + 5, y + 5, w, h);
22     }*/
23 
24        
25   }

聯繫我們

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