Article Directory
What is the Richter Substitution Principle
In layman's terms: "A derived class (subclass) object can replace its base class (superclass) object in a program. The
Richter's substitution principle is one of the important ways to realize the open and close principle, because the base class object is used everywhere. You can use subclass objects, so try to use the base class type to define the object in the program, and then determine the subclass type at runtime, and replace the parent class object with the subclass object.
Type conversion
Display conversion: the parent class object is converted to the child class object using coercion
case1
Person p =new Teacher();
Teacher t =(Teacher)p;//强制转换
t.SayHi();
Implicit conversion: direct conversion of subclass objects to parent objects
case2
Student stu =new Student();
Person p =stu;//隐式转换
p.Show();
Keyword is/as conversion
is conversion: the return is bool type
as conversion: if the conversion can't be done, no exception is returned and null is returned
//关键字is转换
Person p =new Student();//父类转换为子类
bool result = p is Teacher;
if(result)
{
Teacher t =(Teacher)p;
}
else
{
Console.writeline("转换不了");
}
Console.ReadKey();
//关键字as转换
Teacher t =new Teacher();//子类转换为父类
Person p = t as Person;
p.PerShow();
Person p =new Teacher();//父类转换为子类
Teacher t =p as Teacher