请参阅下面的代码(C#):
Control button = new Button(100, 200, "Click Me!");
Control textBlock = new TextBlock(20, 20, "Hello World!");
List<Control> controls = new List<Control>();
controls.Add(button);
controls.Add(textBlock);
foreach (Control ctrl in controls)
{
ctrl.DrawMe(); //The objects will behave polymorphically, because they derive from
//a shared base class.
}
Control 是我自己创建的一个抽象类。如果我将声明中的 Control 更改为它们的等效派生类(如下所示),我将获得完全相同的功能。这是为什么?对抽象基类而不是派生类进行赋值有什么区别吗?
Button button = new Button(100, 200, "Click Me!");
TextBlock textBlock = new TextBlock(20, 20, "Hello World!");