【computerconception】------向下转型,向上转型
定义:
向上转型:子类对象转型成父类对象。此处的父类对象可以是接口。
向下转型:父类转型成子类就是向下转型。
对比:这两个是郑浩相反,子类转型成父类是向上转型,反过来说,父类转型成子类就是向下转型。
父类:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceBridge3._1
{
classHandsetGame
{
publicvirtualvoidRun()
{ }
}
}
子类 M和N
<pre name="code" class="csharp">usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceBridge3._1
{
classHandsetMGame:HandsetGame
{
publicoverridevoidRun()
{
Console.WriteLine("运行M品牌手机游戏!");
}
}
classHandsetNGame :HandsetGame
{
publicoverridevoidRun()
{
Console.WriteLine("运行 N品牌手机游戏!");
}
}
}
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceBridge3._1
{
classProgram
{
staticvoidMain(string[]args)
{
HandsetMGamegame=newHandsetMGame();
HandsetNGamegame2=newHandsetNGame();
game.Run();
game2.Run();
}
}
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceBridge3._1
{
classProgram
{
staticvoidMain(string[]args)
{
//现在
//向上转型upcasting,father f1=new son();
HandsetGamegame=newHandsetMGame();
HandsetGamegame2=newHandsetNGame();
game.Run();
game2.Run();
}
}
}
小结:
1、 向上转型upcasting:子类赋给父类;向下转型downcasting:父类转型成子类。向上转型不用强制转换
Father f1= new Son();
2、向下转型,是要强制转换的,f1就是一个指向子类对象的父类引用。把f1赋给子
类引用s1,即Son s1=(Son)f1;其中f1前面的(Son)必须加上,进行强制转换。
3、父类引用指向子类对象,而子类引用不能指向父类对象。