今天进行了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(); | |
} | |
} | |
} |