2024-11-14《继续c#学习》
今天进行了C#的学习,继续了解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; | |
} | |
// 派生类 | |
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(); | |
} | |
} | |
} |
我们也可以进行多重继承:
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(); | |
} | |
} | |
} |
分类:
软件需求与分析
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)