c#继承类实例

匿名 (未验证) 提交于 2019-12-02 22:06:11
 

在现有类(基类、父类)上建立新类(派生类、子类)的处理过程称为继承。派生类能自动获得基类的除了构造函数和析构函数以外的所有成员,可以在派生类中添加新的属性和方法扩展其功能。

 

继承的特性:

 

可传递性:C从B派生,B从A派生,那么C不仅继承B也继承A。

 

单一性:只能从一个基类中继承,不能同时继承多个基类继承中的访问修饰符base和this关键字基类的构造函数和析构函数不能被继承的。但可以使用关键字base来继承基类的构造函数。

 

C#中的base关键字代表基类,使用base关键字可以调用基类的构造函数、属性和方法。

 
namespace InheritanceApplication {    class Shape     {       public void setWidth(int w)       {          width = w;       }       public void setHeight(int h)       {          height = h;       }       protected int width;       protected int height;    }     // 派生类    class Rectangle: Shape    {       public int getArea()       {           return (width * height);        }    }        class RectangleTester    {       static void Main(string[] args)       {          Rectangle Rect = new Rectangle();           Rect.setWidth(5);          Rect.setHeight(7);           // 打印对象的面积          Console.WriteLine("总面积: {0}",  Rect.getArea());          Console.ReadKey();       }    } }

文章来源: c#继承类实例
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!