码迷,mamicode.com
首页 > 其他好文 > 详细

里氏转换

时间:2014-10-12 23:51:38      阅读:649      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   使用   ar   strong   sp   

里氏转换
子类可以赋值给父类
如果父类中装的是子类,可以将父类转换成子类
可以使用关键字as/is转换

    class Program
    {
        static void Main(string[] args)
        {
            //子类赋值给父类
            Person p = new Student();
            //父类中装的是子类,可以将父类转换成子类
            Student s = (Student)p;
            //使用as关键字转换 转换是被返回null
            Teacher t = p as Teacher;
            //使用关键字is转换
            if (p is Teacher)
            {
                Console.WriteLine("转换成功");
            }
            else
            {
                Console.WriteLine("转换失败");
            }

        }
    }

 

bubuko.com,布布扣
 public class Person
    {
        public string Name
        {
            get;
            set;
        }
    }
父类Person
bubuko.com,布布扣
    public class Student : Person
    {
        public int ID
        {
            get;
            set;
        }
    }
子类Student
bubuko.com,布布扣
    public class Teacher:Person
    {
        public double Salary
        {
            get;
            set;
        }
    }
子类Teacher

 

里氏转换

标签:style   blog   http   color   os   使用   ar   strong   sp   

原文地址:http://www.cnblogs.com/amixc/p/4021112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!