1、里氏转换
1)、子类可以赋值给父类
2)、如果父类中装的是子类对象,那么可以讲这个父类强转为子类对象。
(为方便阅读类都写在一个类文件中)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
namespace 里式转化 { class Program { static void Main(string[] args) { //里式转换1:子类对象可以赋值给父类的对象 //Prson s = new Prson(); //Student k = new Student(); Prson s = new Student();//父类中装的子类对象 //里式转换2:如果父类中装的子类的对象则可以吧父类强转为子类对象 Student ss = (Student)s; } } public class Prson { public void CHLS() { Console.WriteLine("我是人类"); } } public class Student:Prson { public void Say() { Console.WriteLine("我是一个学生"); } } } |
其中is as表示是否能将父类转换为子类。
is:表示类型转换,如果能够转换成功,则返回一个true,否则返回一个false
as:表示类型转换,如果能够转换则返回对应的对象,否则返回一个null
具体用法:is
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Prson s = new Student();//父类里面装的子类对象 if (s is Student)//判断是否能将父类转换成子类 { Console.WriteLine("转换成功"); Console.ReadKey(); } else { Console.WriteLine("转换失败"); Console.ReadKey(); } |
具体用法:as
1 2 3 4 5 |
Prson s = new Student();//父类中装的子类对象 Student p = s as Student;//如果能够转换则返回对应的对象,否则返回一个null p.Say();//调用子类方法 |