里式转换

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //1、里氏转换
 6             /*1)、子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替。*/
 7             //Student s = new Student();
 8             Person p = new Student();//s;
 9 
10             /*2)、如果父类中装的是子类对象,那么可以讲这个父类强转为子类对象。*/
11             //is的用法
12             if (p is Student)
13             {
14                 Student ss = (Student)p;
15                 ss.StudentSayHello();
16             }
17             else
18             {
19                 Console.WriteLine("转换失败");
20             }
21             Console.ReadKey();
22             //as的用法
23             Student t = p as Student;
24             t.StudentSayHello();
25             Console.ReadKey();
26         }
27     }
1     public class Person
2     {
3         public void PersonSayHello()
4         {
5             Console.WriteLine("我是父类");
6         }
7     }
Person
1     public class Student : Person
2     {
3         public void StudentSayHello()
4         {
5             Console.WriteLine("我是学生");
6         }
7     }
Student : Person
1     public class Teacher : Person
2     {
3         public void TeacherSayHello()
4         {
5             Console.WriteLine("我是老师");
6         }
7     }
Teacher : Person

 

posted @ 2020-09-21 16:20  技术不够脸来凑  阅读(136)  评论(0)    收藏  举报