抽象类密封类
使用 abstract 关键字可以创建不完整且必须在派生类中实现的类和类成员。
使用 sealed 关键字可以防止继承以前标记为 virtual 的类或某些类成员。
抽象类不能实例化。 抽象类的用途是提供一个可供多个派生类共享的通用基类定义。 例如,类库可以定义一个抽象类,将其用作多个类库函数的参数,并要求使用该库的程序员通过创建派生类来提供自己的类实现。
抽象类也可以定义抽象方法。 方法是将关键字 abstract 添加到方法的返回类型的前面。
密封类不能用作基类。 因此,它也不能是抽象类。 密封类禁止派生。 由于密封类从不用作基类,所以有些运行时优化可以略微提高密封类成员的调用速度。
在对基类的虚成员进行重写的派生类上,方法、索引器、属性或事件可以将该成员声明为密封成员。 在用于以后的派生类时,这将取消成员的虚效果。 方法是在类成员声明中将 sealed 关键字置于 override 关键字的前面。
public abstract class Shape
{
private string name;
public string Id
{
get
{
return name;
}
set
{
name = value;
}
}
public Shape(string s)
{
Id = s;
}
public abstract double Area
{
get;
}
public override string ToString()
{
return Id + " Area = " + string.Format("{0:F2}", Area);
}
}
public class Square : Shape
{
private int side;
public Square(string id, int _side)
: base(id)
{
this.side = _side;
}
public override double Area
{
get { return side* side; }
}
}
public class Circle : Shape
{
private int radius;
public Circle(string id, int _radius)
: base(id)
{
this.radius = _radius;
}
public override double Area
{
get { return radius * radius * 3.14d; }
}
}
public class Rectangle : Shape
{
private int width;
private int length;
public Rectangle(string id, int _width, int _length)
:base(id)
{
this.width = _width;
this.length = _length;
}
public override double Area
{
get { return width * length; }
}
}
class Program
{
static void Main(string[] args)
{
List<Shape> shape = new List<Shape>(3);
shape.Add(new Square("Square",5));
shape.Add(new Circle("Circle",5));
shape.Add(new Rectangle("Rectangle",5,6));
foreach(Shape item in shape)
{
Console.WriteLine(item.ToString());
}
Console.ReadKey();
}
}
4万+

被折叠的 条评论
为什么被折叠?



