1)子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替
2)如果父类里装的是子类对象,那么可以将这个父类强转为子类对象
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 里氏转换 { class Program { static void Main(string[] args) { //1)子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替 //Student s = new Student(); Person p = new Student (); //string str=string.Join("|",new string[] { "1", "2", "3" }); //Console.WriteLine(str); //Console.ReadKey(); //2)如果父类里装的是子类对象,那么可以将这个父类强转为子类对象 Student ss = (Student)p;//这里的p是装在父类里的子类对象,就是上面的那句Person p = new Student (); ss.StudentSayHeello(); Console.ReadKey(); } } public class Person { public void PersonSayHello() { Console.WriteLine("我是父类"); } } public class Student : Person { public void StudentSayHeello() { Console.WriteLine("我是子类"); } } public class Teacher : Person { public void TeacherSayHello() { Console.WriteLine("我是子类"); } } }
is:表示类型转换,仅判断 ,如果能够转换成功,则返回一个true,否则就转换成一个false
as:表示类型转换,先判断,再转换。如果是的,返回一个对应的对象,如果不是的话,返回一个空
练习://创建10个对象,通过一个循环去调用他们各自打招呼的方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 里氏转换练习 { class Program { static void Main(string[] args) { //创建10个对象,通过一个循环去调用他们各自打招呼的方法 Person[] pers = new Person[10]; Random r = new Random();//新建一个随机数 for (int i = 0; i < pers.Length; i++) { int rNumber = r.Next(1, 6);//确定一个变量为随机数,范围从1到5 switch (rNumber)//1-6 { case 1: pers[i] = new Student(); break; case 2: pers[i] = new Teacher(); break; case 3: pers[i] = new Person(); break; case 4: pers[i] = new HandsomeBoy(); break; case 5: pers[i] = new Beauty(); break; } } for (int i = 0; i < pers.Length; i++) { //pers[i].PersonSayHi(); if (pers[i] is Student) { ((Student)pers[i]).StudentSayHi(); } else if (pers[i] is Teacher) { ((Teacher)pers[i]).TeacherSayHi(); } else if (pers[i] is HandsomeBoy) { ((HandsomeBoy)pers[i]).HandsomeBoySayHi(); } else if (pers[i] is Beauty) { ((Beauty)pers[i]).BeautySayHi(); } else { pers[i].PersonSayHi(); } } Console.ReadKey(); } } public class Person { public void PersonSayHi() { Console.WriteLine("我是人类"); } } public class Student : Person { public void StudentSayHi() { Console.WriteLine("我是学生"); } } public class Teacher : Person { public void TeacherSayHi() { Console.WriteLine("我是老师"); } } public class Beauty : Person { public void BeautySayHi() { Console.WriteLine("我是美女"); } } public class HandsomeBoy : Person { public void HandsomeBoySayHi() { Console.WriteLine("我是帅哥"); } } }