C#中子类与父类的相互转换

1.父类不能直接强制转换成子类
2.子类可以强制转换成父类,但是在父类中只能取父类的字段与方法因此在一个父类对应多个子类的时候,不知道具体是哪个子类的时候,就可以先声明一个父类的类型。(如例1)
3.由1,2知,父类不能直接强制转换成子类,但是可以通过间接的方法进行转换,例1中有所体现:将子类转换成父类,然后再把父类转换成子类,如例2。
特别说明:虽然可以通过间接方式将父类转成子类,但实际用处不大,因为需要一个临时的子类来进行转换,因为其实可以直接在子类直接转换,所以实际用处不大。

(下例只适用于从栈制到堆的行为,即装箱拆箱)
例一:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace testApplication  
{  
 public class Parent  
    {  
        public int a=0;  
    }  
    public class Son:Parent  
    {  
        public int b=0;  
        public int run()  
        {  
            return a + b;  
        }  
    }  
    public class Son2 : Parent  
    {  
        public string c = "Son2";  
        public int run()  
        {  
            return a;  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            //不知道具体是哪个子类,因此先用父类来声明  
            List<Parent> sL = new List<Parent>();  
            Son cs1 = new Son(); cs1.b = -1;  
            Son cs2 = new Son(); cs2.b = -2;  
            sL.Add(cs1);  //子类可以强制转换成父类,即装箱 
            sL.Add(cs2);  
            for (int i = 0; i < 2;i++ )  
            {  
                //这里需要把父类再强制转换成子类(因为是装箱而来的父类,可以对其进行拆箱成子类)  
                //取出子类中的字段,即拆箱  
                Console.WriteLine(((Son)sL[i]).b);  
            }  
            Console.ReadLine();  
        }  
    }  

}  

例二:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace testApplication  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            Parent pa = new Parent();  
            pa.a=9;  
            //设置一个临时的子类  
            Son tmpt = new Son();  
            tmpt.a = 9;  
            //进行装箱  
            pa = (Parent)tmpt;  
            //进行拆箱  
            Son cson = (Son)pa;  
            Console.WriteLine(cson.a);  
            Console.ReadLine();  
        }  
    }  
    public class Parent  
    {  
        public int a=0;  
    }  
    public class Son:Parent  
    {  
        public int b=0;  
        public int run()  
        {  
            return a + b;  
        }  
    }  
    public class Son2 : Parent  
    {  
        public string c = "Son2";  
        public int run()  
        {  
            return a;  
        }  
    }  
}  
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值