一、虚方法与方法重写
修改基类的某些方法的执行逻辑
使用override关键词
作用:实现多态
重写基类必须将原有方法的基类设置成virtual,然后override重写
Program.cs
class Program
{
static void Main(string[] args)
{
var shapeList = new List<Shape>();
shapeList.Add(new Circle());
shapeList.Add(new Rectangle());
var canvas = new Canvas();
canvas.DrawShapes(shapeList);
Console.Read();
}
}
Shape.cs
public class Circle : Shape
{
public override void Draw()
{
//base.Draw();//调用基类方法
Console.WriteLine("画圆");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
//base.Draw();//调用基类方法
Console.WriteLine("画方");
}
}
public class Shape
{
public int Width { get; set; }
public int Height { get; set; }
public Position Position { get; set; }
public virtual void Draw()//基类中使用virtual定义方法
{
Console.WriteLine("绘制图案");
}
}
ShapeType.cs
public enum ShapeType
{
Circle,
Rectangle
}
Position.cs
public class Position
{
public int X { get; set; }
public int Y { get; set; }
}
Canvas.cs
class Canvas
{
public void DrawShapes(List<Shape> shapes)
{
foreach (var shape in shapes)
{
shape.Draw();
}
}
}
二、多态
可替换性
可扩充性
接口性
灵活性
简化性
三、抽象类与抽象成员
abstract关键词
声明修饰符;可以修饰类、方法、属性;只有声明、没有逻辑,不会被实现;
抽象规则
1.声明为abstract以后,整个属性或者方法不可以有代码实现
2.当某个成员被声明为abstract,整个class都需要被声明为abstract;同时对方法进行重写时,不需要使用virtual关键词
3.派生类必须实现抽象类中所有的抽象方法和抽象属性
4.抽象类不可以被实例化
shape.cs
public class Circle : Shape
{
public override void Draw()
{
//base.Draw();//调用基类方法
Console.WriteLine("画圆");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
//base.Draw();//调用基类方法
Console.WriteLine("画方");
}
}
public abstract class Shape
{
public int Width { get; set; }
public int Height { get; set; }
public Position Position { get; set; }
public abstract void Draw();
}
四、密封类和密封成员
·使用sealed修饰符
·防止类继承、防止派生类重写
·sealed修饰符不仅可以修饰class,也可以修饰类成员