里氏转换
子类可以赋值给父类
如果父类中装的是子类,可以将父类转换成子类
可以使用关键字as/is转换
class Program { static void Main(string[] args) { //子类赋值给父类 Person p = new Student(); //父类中装的是子类,可以将父类转换成子类 Student s = (Student)p; //使用as关键字转换 转换是被返回null Teacher t = p as Teacher; //使用关键字is转换 if (p is Teacher) { Console.WriteLine("转换成功"); } else { Console.WriteLine("转换失败"); } } }
public class Person { public string Name { get; set; } }
父类Person
public class Student : Person { public int ID { get; set; } }
子类Student
public class Teacher:Person { public double Salary { get; set; } }
子类Teacher
时间: 2024-10-07 01:57:52