Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 261

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 261
_higrid.net-嗨网
当前位置:嗨网首页>书籍在线阅读

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 266

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 266

Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 266

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 266

10.2.3 方法重载、重写和隐藏

在基类和派生类中可以存在同名方法,这些同名的方法可以分为重载、重写和隐藏3种类型。

1.重载

重载是在同一个作用域内发生(比如一个类里面),定义一系列同名方法,但是方法的参数列表不同,就是签名不同,签名由方法名和参数组成。能通过传递不同的参数来决定到底调用哪一个同名方法。注意返回值类型不同不能构成重载,因为签名不包括返回值。

2.重写

基类方法中使用virtual关键字声明的方法和派生类中使用override关键字声明的方法名称相同,参数列表也相同,就是基类方法和派生类方法的签名相同,实现了派生类重写基类中的同名方法。

3.隐藏

基类中的方法不声明为virtual(默认为非虚方法),在派生类中声明与基类同名时,需使用new关键字,以隐藏基类同名方法。

如在Person类中声明两个Display方法用于显示Person的信息演示重载,在其派生类中实现对Display重写和隐藏的代码如下。

01  public  virtual void  Display()                  //定义成虚拟方法,没有参数
02  {
03          Console.WriteLine("{0}是{1}性,年龄为{2}", this._name, this._gender, this._age);
04  }
05  public  void Display(string id)                  //同名方法实现重载
06  {
07          this.Display ();                         //调用第1行的无参Display方法
08          Console.WriteLine (" 身份证号是:{0}",id); //增加输出身份证号的信息
09  }

在派生类Student类中声明如下方法使用隐藏。

01  public override void Display()          //重写基类Display()
02  {
03          Console.WriteLine("这是一个学生:"); 
04          base.Display();                //调用基类的Display方法
05  }
06  public new void Display(string no)     //使用new隐藏基类
07  {
08          Console.WriteLine("这是一个学生:");
09          base.Display();                //调用基类的Display方法
10          Console .WriteLine ("学生的学号是:{0}",no);
11  }


Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 276

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 276

Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 276

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 276