本文主要是介绍C#自学24一继承:里氏转换+protected用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、里氏转换
1)、子类可以赋值给父类
2)、如果父类中装的是子类对象,那么可以讲这个父类强转为子类对象。
2、
子类对象可以调用父类中的成员,但是父类对象永远都只能调用自己的成员。
3、
is:表示类型转换,如果能够转换成功,则返回一个true,否则返回一个false
as:表示类型转换,如果能够转换则返回对应的对象,否则返回一个null
4、protected
受保护的:可以在当前类的内部以及该类的子类中访问。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace _03里氏转换练习
{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);switch (rNumber)//1-6{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 MeiLv();break;case 5: pers[i] = new YeShou();break;case 6: pers[i] = new Person();break;}}for (int i = 0; i < pers.Length; i++){// pers[i].PersonSayHi();if (pers[i] is Student){((Student)pers[i]).StudentSayHi();// pers[i].PersonSayHi();}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 YeShou){((YeShou)pers[i]).YeShouSayHi();}else if (pers[i] is MeiLv){((MeiLv)pers[i]).MeiLvSayHi();}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 MeiLv : Person{public void MeiLvSayHi(){Console.WriteLine("我是镁铝");}}public class ShuaiGuo : Person{public void ShuaiGuoSayHi(){Console.WriteLine("我是帅锅");}}public class YeShou : Person{public void YeShouSayHi(){Console.WriteLine("我是野兽");}}}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace _04protected访问修饰符
{class Program{static void Main(string[] args){//public privatePerson p = new Person();}}public class Person{protected string _name;public string Name{get { return _name; }set { _name = value; }}}public class Student : Person{public void Test(){ }}
}
这篇关于C#自学24一继承:里氏转换+protected用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!