23.里式转换法则

里氏转换

1)、子类可以赋值给父类
2)、如果父类中装的是子类对象,那么可以讲这个父类强转为子类对象。

例如:

namespace Demo {


    class Person {
    
    }

    class Student : Person {

     
    }

    class Program {

        static void Main(string[] args) {

            Person p = new Student();

            Student s = (Student)p;
            
            Console.ReadKey();

        }
    }


}

注意:子类对象可以调用父类中的成员,但是父类对象永远都只能调用自己的成员。

is和as

is:表示类型转换,如果能够转换成功,则返回一个true,否则返回一个false
as:表示类型转换,如果能够转换则返回对应的对象,否则返回一个null

is的用法

Person p = new Student();

if (p is Student) {
    Student s = (Student)p;
    s.Eat();
} else {
    Console.WriteLine("转换失败");
}

运行结果:

as的用法

namespace Demo {


    class Person {

        public void Eat() {
            Console.WriteLine("吃饭");
        }
    }

    class Student : Person {

        public void Write(){
            Console.WriteLine("写作业");
        }
     
    }

    class Program {

        static void Main(string[] args) {

            Person p = new Student();

            Student s=p as Student;
            s.Write();
   
            Console.ReadKey();

        }
    }


}

运行结果:

如果是p=new Person()的话,那么p as Student会返回为null,调用方法时就会报异常。

p = new Person();
Student t = p as Student;
t.Write();

运行结果:

原文地址:https://www.cnblogs.com/lz32158/p/12915984.html