using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C03LSP
{
class Program
{
static void Main(string[] args)
{
//里氏替换原则:LSP 子类可以替换父类的位置,并且程序的功能不受影响.
//父类有的功能子类都有,所以不影响程序的功能
//父类变量指向了1个子类对象.
//当1个父类变量指向1个子类对象的时候 只能通过这个父类变量调用父类的成员.子类独有的成员无法调用.
Person p = new Person();
p.SayHi();//调用父类的
Student s = new Student();
s.SayHi();//调用子类的.
//运行时绑定.
Person p1 = new Student();
p1.SayHi();//父类的.
p1.Age = 19;
p1.Name = "小花";
p1.SayHi();
//子类变量不能指向1个父类对象.
//必须要有继承关系 才可以使用强制转换.
//如果1个父类变量指向的就是1个父类对象 将这个父类对象转换为子类对象的会报异常.
//Student s0 = (Student)p;//会报错.
//如果1个父类变量指向了1个子类对象 那么可以将这个父类变量转换为为子类对象.
Person p = new Person();
Student s = new Student();
Person p1 = new Student();
//Student s1 = (Student)p1;
//is 判断变量是否是指定的类型
bool b = p is Person; //
b = p is Student; //因为 1个Person不一定是Student
b = p is Object; //因为Person从Object继承
b = p is Program; //如果没有继承关系 表达式的值永远都是false
b = p1 is Person; //父类变量指向子类对象 父类变量本身是Person 指向的对象学生也是1个Person
b = p1 is Student; //p1变量指向的对象本来就是1个Student 所以true
b = p1 is Program; //如果没有继承关系 表达式的值永远都是false
b = p1 is object;
//首先判断变量是不是要转换的类型
if (p1 is Student)
{
Student s2 = (Student)p1;
}
//as 转换.
// Student s3 = (Student)p; //有可能会报异常
//as转换 如果转换成功 引用指向s4 如果转换失败 不报异常 返回null
Student s4 = p as Student;
s4.StuNo = "123";
Console.WriteLine(b);
// Program pr = new Program();
//s1 = (Student)pr; 不行 因为他们没有继承关系.
Console.ReadKey();
}
}
}
Person类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C03LSP
{
class Person
{
public int Age { get; set; }
public string Name { get; set; }
private double height;
public void SayHi()
{
Console.WriteLine("我是父类的方法");
}
}
}
Student类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C03LSP
{
class Student:Person
{
public string StuNo { get; set; }
//public void SayHi(int num)
//{
// Console.WriteLine("我是子类的方法。。。。。"+num);
//}
public void SayHi()
{
Console.WriteLine("我是子类的方法。。。。。");
}
public void SayHi1()
{
Console.WriteLine("我是子类的方法。。。。。");
}
}
}