using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04里氏转换
{
class Program
{
static void Main(string[] args)
{
//里氏转换:
//1.子类可以赋值给父类
//2.如果父类中装的是子类对象,那么可以将这个父类转换为相应的子类对象
//Person p = new Student();
//判断是否可以转换成的子类
//1.is:表示类型转换,若转换成功,返回true,否则返回false
//2.as:表示类型转换,若转换成功,返回相应子类的对象,否则,返回null
//is方法
//if(p is Student)
//{
// Student ss = (Student)p;
//}
//else
//{
// Console.WriteLine("转换失败");
//}
//Console.ReadKey();
//as方法
//Student t = p as Student;
//Console.ReadKey();
//创建10个对象,通过一个循环 去调用
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 MeiLv();
break;
case 4:
pers[i] = new ShuaiGe();
break;
case 5:
pers[i] = new YeShou();
break;
case 6:
pers[i] = new Person();
break;
}
}
for (int j = 0; j < pers.Length; j++)
{
//pers[i].PersonSayHi();这样的方法是不可以的,返回的是父类的方法
if (pers[j] is Student)
{
((Student)pers[j]).StudentSayHi();
}
else if (pers[j] is Teacher)
{
((Teacher)pers[j]).TeacherSayHi();
}
else if (pers[j] is MeiLv)
{
((MeiLv)pers[j]).MeiLvSayHi();
}
else if (pers[j] is ShuaiGe)
{
((ShuaiGe)pers[j]).ShuaiGeSayHi();
}
else if (pers[j] is YeShou)
{
((YeShou)pers[j]).YeShouSayHi();
}
else
{
pers[j].PersonSayHi();
}
}
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04里氏转换
{
public class Person
{
public void PersonSayHi()
{
Console.WriteLine("我是人类");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04里氏转换
{
public class ShuaiGe:Person
{
public void ShuaiGeSayHi()
{
Console.WriteLine("我是帅锅");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04里氏转换
{
public class Student:Person
{
public void StudentSayHi()
{
Console.WriteLine("我是学生");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04里氏转换
{
public class Teacher:Person
{
public void TeacherSayHi()
{
Console.WriteLine("我是教师");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04里氏转换
{
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 _04里氏转换
{
public class MeiLv:Person
{
public void MeiLvSayHi()
{
Console.WriteLine("我是镁铝");
}
}
}
04里氏转换
最新推荐文章于 2021-09-23 23:03:57 发布