c# 里式转换
is—表示类型转换,如果转换成功就返回true否则就是false
as—表示类型转换,如果转换成功就返回该对象 否则就是null
1)、子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替。(配合is关键字判断是否可以转换)
(如:Person s = new Student();)
2)、如果这个父类中装的是子类对象,那么可以将这个父类强转为子类对象。
(如:Student p = (Student)s;)
子类对象可以调用父类中的成员,但是父类对象永远都只能调用自己的成员。
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 41 42 43 44 45 46 47 48 | class Program { static void Main( string [] args) { //子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替 Father dg = new Children(); dg.SayHello(); //dg装的是子类,但是仍是父类,父类对象永远都只能调用自己的成员 //如果这个父类中装的是子类对象,那么可以将这个父类强转为子类对象。 Father ss = new Children(); Children fatherSwitch = (Children)ss; fatherSwitch.SayHello(); //变为子类 //转换判断 is(bool) as(obj or null) if (dg is Children) { Console.WriteLine( "我是父类装载的是子类" ); } else { Console.WriteLine( "" ); } //转换判断 as(obj or null) Children a = ss as Children; //ss转换children成功返回obj,否则null Console.ReadKey(); } } public class Father { public string a = "我是父类属性" ; public void SayHello() { Console.WriteLine( "我是父类" ); } } public class Children:Father { public string b = "我是子类属性" ; public void SayHello() { Console.WriteLine( "我是子类" ); } } |
练习:随机执行不同子类方法
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | static void Main( string [] args) { Teacher li = new Teacher(); Student wang = new Student(); Repoter zhang = new Repoter(); //创建父类数组用来装载子类 People[] MyChildren = new People[3]; //for循环装载子类 for ( int i = 0; i < MyChildren.Length; i++) { Random rm = new Random(); int rms = rm.Next(0, 3); //random随机数短时间内相同 switch (rms) { case 0 :MyChildren[i] = new Teacher(); break ; case 1: MyChildren[i] = new Student(); break ; case 2: MyChildren[i] = new Repoter(); break ; } } for ( int i = 0; i <MyChildren.Length; i++) { if (MyChildren[i] is Student ) //is判断 { ((Student)MyChildren[i]).SayHello(); //注意写法 } else if (MyChildren[i] is Teacher) { ((Teacher)MyChildren[i]).SayHello(); } else { ((Repoter)MyChildren[i]).SayHello(); } } Console.ReadKey(); } }<br> public class People { public void SayHello() { Console.WriteLine( "我是父类" ); } } public class Teacher:People { public new void SayHello() //new显式隐藏父类同名函数,即覆盖 { Console.WriteLine( "我是教师" ); } } public class Student : People { public new void SayHello() { Console.WriteLine( "我是学生" ); } } public class Repoter: People { public new void SayHello() { Console.WriteLine( "我是记者" ); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~