【computer conception】------向下转型,向上转型


【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品牌手机游戏!");
 
       }
   }
}


 

 

客户端:常用的实现方法1:

  

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、父类引用指向子类对象,而子类引用不能指向父类对象。





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值