您的位置:首页 > 编程语言 > C#

C#里氏转换

2016-04-05 14:50 225 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 里氏转换
{
class Program
{
static void Main(string[] args)
{
/* 里氏转换
* 1、子类可以赋值给父类(如果一个方法需要父类作为参数,我们可以传递一个子类对象)
2、如果父类中装的是子类对象,则可以将这个父类强转为子类对象
*/
Person p = new Person();
p.PersonSayHello();

Person p1 = new Student();
if (p1 is Student)
{
((Student)p1).StudentSayHello();
}
else
{
Console.WriteLine("转换失败");
}
Console.ReadKey();

Student ss = p1 as Student;
ss.StudentSayHello();
Console.ReadKey();
}

public class Person
{
public void PersonSayHello()
{
Console.WriteLine("Person");
}
}

public class Student : Person
{
public void StudentSayHello()
{
Console.WriteLine("student");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#