请教,为什么C#中常常实例化子类,定义却是父类类型
如题,看很多源代码中都是实例化子类,然后定义的是它的父类类型,不明白这样做有什么好处呢。
我写了个大致例子
public partial class Form1 : Form
{
private father _father;
public Form1()
{
InitializeComponent();
this._father = new sun();
}
}
abstract class father
{
protected int a = 10;
public void b()
{
}
protected abstract void c();
}
class sun : father
{
public void d()
{
}
protected override void c()
{
}
}
_father 对象定义的即是父类的类型,但实际上是实例化了子类。很奇怪为什么常常这样做,这样做有什么好处呢,在什么情况下需要这么做呢?在这里向大家请教了