美文网首页
里式转换

里式转换

作者: 任人渐疏_Must | 来源:发表于2021-06-18 08:24 被阅读0次

    /*里式转换
     * 1.子类可以赋值给父类
     * 2.如果父类中装的是子类对象,那么可以将这个父类强转为子类对象
     * 
     * 3.is:表示类型转换,如果转换成功,返回一个true
     *   as:转换失败,则返回Null
     * 
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            //Student s = new Student();
            //1.子类可以赋值给父类:如果有一个地方需要父类作为参数,我们可以给一个子类代替
            //Person p = s;
            Person p = new Student();

            //2.如果父类中装的是子类对象,那么可以将这个父类强制转为子类对象
            Student s = (Student)p;
            s.StudentSayHello();

            //is
            if(p is Teacher)
            {
                Teacher t = (Teacher)p;
                t.TeacherSayHello();
            }
            else
            {
                Console.WriteLine("转换失败!");
            }


            //as
          //  Teacher t = p as Teacher;
            
            Console.ReadKey();
           
        }
    }

    public class Person
    {
        public void PersonSayHello()
        {
            Console.WriteLine("我是父类");
        }
    }

    public class Student : Person
    {
        public void StudentSayHello()
        {
            Console.WriteLine("我是学生");
        }
    }

    public class Teacher : Person
    {
        public void TeacherSayHello()
        {
            Console.WriteLine("我是老师");
        }
    }

相关文章

网友评论

      本文标题:里式转换

      本文链接:https://www.haomeiwen.com/subject/yygmeltx.html