标签:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /*里氏转换 * 1,子类可以赋值给父类:如果一个地方需要一个父类作为参数,可以给一个子类代替 * 2,如果父类中装的是子类对象,那么可以将这个父类对象强制转换成子类对象 * * 子类对象可以调用父类中的成员,但是父类对象只能调用自己的成员 * **/ namespace _01里氏转换 { class Program { static void Main(string[] args) { //子类可以赋值给父类 //Student s = new Student(); Person p = new Student();//s //string str = string.Join("|", new string[] { "1", "2", "3", "4" }); //Console.WriteLine(str); //Console.ReadKey(); //如果父类中装的是子类对象,那么可以将这个父类对象强制转换成子类对象 Student ss = (Student)p; ss.SayHello(); Console.ReadKey(); } } }
is:表示类型转换,如果能够转换成功,则返回true,否则返回false
if(p is Teacher) { Teacher ss = (Teacher)p; ss.TeacherSayHello(); } else { Console.WriteLine("转换失败"); }
as:表示类型转换,如果能够转换则返回对应的对象,否则返回null
练习
创建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个对象,通过循环,调用他们各自打招呼的方法 //Student s = new Student(); //Person p = new Person(); //ShuaiGuo sg = new ShuaiGuo(); Person[] pers = new Person[10]; Random r = new Random(); for (int i = 0; i < pers.Length; i++) { int rNumber = r.Next(1, 7);//此范围表示1-6 switch (rNumber) { case 1: pers[i] =new Student(); break; case 2: pers[i] = new Teacher(); break; case 3: pers[i] = new ShuaiGuo(); break; case 4: pers[i] = new MeiNv(); break; case 5: pers[i] = new YeShou(); break; case 6: pers[i] = new Person(); break; }//switch }//for for (int i = 0; i < pers.Length; i++) { if(pers[i] is Student) { ((Student)pers[i]).StudentSayHi(); } else if(pers[i] is Teacher) { ((Teacher)pers[i]).TeacherSayHi(); } else if(pers[i] is ShuaiGuo) { ((ShuaiGuo)pers[i]).ShuaiGuoSayHi(); } else if(pers[i] is MeiNv) { ((MeiNv)pers[i]).MeiNvSayHi(); } else if (pers[i] is YeShou) { ((YeShou)pers[i]).YeShouSayHi(); } else { pers[i].PersonSayHi(); } } Console.ReadKey(); } } }
.Net学习笔记----2015-06-23(继承(里氏转换))
标签:
原文地址:http://www.cnblogs.com/mikie/p/4596637.html