星空网 > 软件开发 > ASP.net

面向对象的基础知识

面向对象的原则:

多组合、少继承;低耦合,高内聚

继承多关注于共同性;多态着眼于差异性

多态

通过继承,一个类可以用作多种类型:可以用作它自己的类型、任何基类型,或者在实现接口时用作任何接口类型。这称为多态性。C# 中的每种类型都是多态的。类型可用作它们自己的类型或用作 Object 实例,因为任何类型都自动将 Object 当作基类型。

 1 public class animal 2   { 3  4     public string SayName() 5     { 6       return "hello im animal"; 7      8     } 9     public string Eat()10     {11 12       return "this is animal's eat";13     }14     public virtual string Call()15     {16     17     return "this is animal's speak";18     }19   }20   public class Bird:animal21   {22     public new string Eat()// 使用新的派生成员替换基成员23     {24       return "this is bird's Eat";25     }26     public override string Call() //重写虚方法27     {28       return "this is Bird's Call";29     }30     31   }

 


 

  1. 多态分为接口多态和继承多态
  2. 若要更改基类的数据和行为,您有两种选择:可以使用新的派生成员替换基成员,或者可以重写虚拟的基成员。
 1 /*继承基类的 eat 和 call 功能*/ 2       /* 3        * result: 4       hello im animal 5       this is bird's Eat 6       this is Bird's Call 7       */ 8       Bird bb = new Bird(); 9       Response.Write(bb.SayName() + "</br>");10       Response.Write(bb.Eat()+"</br>");11       Response.Write(bb.Call() + "</br>");12 13       /*14        *result:15       hello im animal16       this is animal's eat17       this is Bird's Call18       */19       animal ab = new Bird();20       Response.Write(ab.SayName() + "</br>"); 21       Response.Write(ab.Eat() + "</br>");22       Response.Write(ab.Call() + "</br>");

new 修饰符:在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。

当派生类重写某个虚拟成员时,即使该派生类的实例被当作基类的实例访问,也会调用该成员。



        

 

 

封装

封装第一原则:将字段定义为private




原标题:面向对象的基础知识

关键词:面向对象

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流