zoukankan      html  css  js  c++  java
  • C#里面的继承

    举个例子:
    有一个基类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(15153030 );
     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(202020);
    4       sq.Draw(g);//这里使用了上面的来自PaintEventArgs e 的Griphics对象
    5 

    这个时候呢,如果我希望有新的派生类,能同时画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   }

  • 相关阅读:
    memcached连接说明
    在win下启动memcached
    Memcached 查看帮助
    HTTP请求信息和响应信息的格式
    购买服务器配置带宽算法
    PHP删除数组指定下标的值
    tp5 验证器使用
    tp5 验证码功能实现
    layui 关闭当前窗口,刷新父级页面
    layui icon样式1到7
  • 原文地址:https://www.cnblogs.com/lizunicon/p/1174755.html
Copyright © 2011-2022 走看看