1、里式转换
(1)子类可以赋值给父类
(2)如果父类中装的是子类对象,那么可以将这个父类强转为子类对象。
2、子类对象可以调用父类中的成员,但是父类对象永远都只能调用自己的成员.
is:表示类型转换,如果能够转换成功,则返回true否则返回false。
as:表示类型转换,如果能够转换,则返回对应的对象,否则返回null。
using System;
namespace _060_面对对象继承_06_里式转换
{
class Program
{
static void Main(string[] args)
{
Student student = new Student();
//1、子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替。
//Person person = student;
//person.PersonSayHello();
Person person = new Student();
string s = string.Join("|", new string[] { "1", "2", "3", "4", "5" });//new string[]{} --> object 子类赋值给父类
Console.WriteLine(s);
//2、如果父类中装的是子类对象,那么可以将这个父类强转为子类对象
//is的用法
if (person is Student)
{
Student student1 = (Student)person;
student1.StudentSayHello();
}
else
{
Console.WriteLine("转换失败");
}
//as的用法
//Teacher teacher = person as Teacher; 转换失败 teacher中的值为null
Student student2 = person as Student;
student2.StudentSayHello();
Console.ReadKey();
}
}
}
class Person
{
public void PersonSayHello()
{
Console.WriteLine("我是父类");
}
}
class Teacher:Person
{
public void TeacherSayHello()
{
Console.WriteLine("我是老师");
}
}
class Student:Person
{
public void StudentSayHello()
{
Console.WriteLine("我是学生");
}
}
练习:
using System;
namespace _061_里式转换练习
{
class Program
{
static void Main(string[] args)
{
Person[] person = new Person[10];
Random r = new Random();
for (int i = 0; i < person.Length; i++)
{
int rNumber = r.Next(1, 7);
switch (rNumber)
{
case 1:
person[i] = new Student();
((Student)person[i]).StudentSayHi();
break;
case 2:
person[i] = new Beast();
((Beast)person[i]).BeastSayHi();
break;
case 3:
person[i] = new Beauty();
((Beauty)person[i]).BeautySayHi();
break;
case 4:
person[i] = new Handsome();
((Handsome)person[i]).HandsomeSayHi();
break;
case 5:
person[i] = new Teacher();
((Teacher)person[i]).TeacherSayHi();
break;
case 6:
person[i] = new Person();
person[i].PersonSayHi();
break;
default:
break;
}
}
//for (int i = 0; i < person.Length; i++)
//{
// //person[i].PersonSayHi();
// if(person[i] is Student)
// {
// ((Student)person[i]).StudentSayHi();
// }
// else if(person[i] is Beast)
// {
// ((Beast)person[i]).BeastSayHi();
// }
// else if (person[i] is Beauty)
// {
// ((Beauty)person[i]).BeautySayHi();
// }
// else if (person[i] is Handsome)
// {
// ((Handsome)person[i]).HandsomeSayHi();
// }
// else if (person[i] is Teacher)
// {
// ((Teacher)person[i]).TeacherSayHi();
// }
// else
// {
// person[i].PersonSayHi();
// }
//}
Console.ReadKey();
}
}
}
class Person
{
public void PersonSayHi()
{
Console.WriteLine("我是人类");
}
}
class Student:Person
{
public void StudentSayHi()
{
Console.WriteLine("我是学生");
}
}
class Teacher:Person
{
public void TeacherSayHi()
{
Console.WriteLine("我是老师");
}
}
class Beauty:Person
{
public void BeautySayHi()
{
Console.WriteLine("我是美女");
}
}
class Handsome:Person
{
public void HandsomeSayHi()
{
Console.WriteLine("我是帅哥");
}
}
class Beast:Person
{
public void BeastSayHi()
{
Console.WriteLine("我是野兽");
}
}