博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 基础知识复习(七)---继承
阅读量:4579 次
发布时间:2019-06-09

本文共 2264 字,大约阅读时间需要 7 分钟。

继承允许我们根据一个类来定义另一个类,这使得创建和维护应用程序变得更容易。同时也有利于重用代码和节省开发时间。

using System;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(); } } }

当上面的代码被编译和执行时,它会产生下列结果:

总面积: 35

基类的初始化

派生类继承了基类的成员变量和成员方法。因此父类对象应在子类对象创建之前被创建。您可以在成员初始化列表中进行父类的初始化。

下面的程序演示了这点:

using System;namespace RectangleApplication { class Rectangle { // 成员变量 protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("长度: {0}", length); Console.WriteLine("宽度: {0}", width); Console.WriteLine("面积: {0}", GetArea()); } }//end class Rectangle class Tabletop : Rectangle { private double cost; public Tabletop(double l, double w) : base(l, w) { } public double GetCost() { double cost; cost = GetArea() * 70; return cost; } public void Display() { base.Display(); Console.WriteLine("成本: {0}", GetCost()); } } class ExecuteRectangle { static void Main(string[] args) { Tabletop t = new Tabletop(4.5, 7.5); t.Display(); Console.ReadLine(); } } }

C# 不支持多重继承。但是,您可以使用接口来实现多重继承。下面的程序演示了这点:

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

转载于:https://www.cnblogs.com/xyzrobot/p/7517869.html

你可能感兴趣的文章
如何在MyBatis中优雅的使用枚举
查看>>
SCVMM 2012 SP1 安装
查看>>
可做爬虫的jsoup常用方法,附异步请求实现
查看>>
redis分布式工具类 ----RedisShardedPoolUtil
查看>>
H5新属性FileReader实现选择图片后立即显示在页面上
查看>>
LEDAPS1.3.0版本移植到windows平台----HuPm参数初始化模块
查看>>
【微服务架构】SpringCloud之Hystrix断路器(六)
查看>>
项目复审与事后分析
查看>>
PCA(主分量分析)-转载
查看>>
Hadoop 2.0命令手册
查看>>
SVN 提交项目.a文件缺失 cornerstone设置方法
查看>>
git push不用重复输入用户名和密码(解决方案)
查看>>
委托与事件
查看>>
实现POST服务器
查看>>
Linux下的tar压缩解压缩命令详解
查看>>
大数据项目测试<二>项目的测试工作
查看>>
linux网路IP.设定主机名.ssh .bash命令&通配符
查看>>
mysql 行列动态转换(列联表,交叉表)
查看>>
软件开发模式
查看>>
装机散记--某鱼矿卡和某宝矿卡
查看>>