Список абстрактного типа в C#
Хранить абстрактный тип как готовый объект нельзя, но в списке базового типа удобно собирать разные реализации.
List<Shape> хранит ссылки на объекты
потомков. В цикле вызывают полиморфный метод.
Запишем список фигур и выведем площади:
abstract class Shape
{
public abstract int Area();
}
class Rectangle : Shape
{
public int Width;
public int Height;
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public override int Area()
{
return Width * Height;
}
}
class Square : Shape
{
public int Side;
public Square(int side)
{
Side = side;
}
public override int Area()
{
return Side * Side;
}
}
Создадим список, положим в него прямоугольник и квадрат и выведем площади:
var figures = new List<Shape>();
figures.Add(new Rectangle(3, 4));
figures.Add(new Square(5));
foreach (Shape figure in figures)
{
Console.WriteLine(figure.Area());
}
Создайте List<Figure>,
положите в него объекты Circle
и Rectangle,
выведите площадь каждой фигуры в цикле.