我有以下情况,我想知道 CLR 如何知道要调用哪个方法:
public abstract class Shape
{
public abstract String PrintName();
}
public sealed class Square : Shape
{
public override String PrintName() { return "Square"; }
}
public sealed class Circle : Shape
{
public override String PrintName() { return "Circle"; }
}
然后我实例化每个形状:
Shape square = new Square();
Shape circle = new Circle();
List<Shape> shapes = new List<Shape> { square, circle };
foreach (Shape s in shapes)
{
Console.WriteLine(s.PrintName());
}
// Output:
// Square
// Circle
那么,即使我们在基类型上调用方法,我们如何才能在派生类上调用方法呢?我很困惑这是如何处理的。