里氏转换
2021-08-10 本文已影响0人
扶不起的蝌蚪
里氏转换的特点
- 父类引用指向子类对象
- 如果父类引用指向的是子类对象,那么可以将这个父类强转为子类对象
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Person p = new Student();
}
}
public class Person
{
public void SayTeacher()
{
Console.WriteLine("我是Person类方法");
}
}
public class Student:Person
{
public void SayStudent()
{
Console.WriteLine("我是Student类方法");
}
}
}

将父类强转为子类对象,后便可以正常调用子类的成员
class Program
{
static void Main(string[] args)
{
Person p = new Student();
Student s = (Student)p;
s.
}
}
public class Person
{
public void SayPerson()
{
Console.WriteLine("我是Person类方法");
}
}
public class Student:Person
{
public void SayStudent()
{
Console.WriteLine("我是Student类方法");
}
}

里氏转换的实际应用
如果有方法的参数是父类,那么我们可以传递一个子类给它
比如在string的join方法中,我们可以看到,第二个参数是Object数组,而Object是所有类的基类,那么我们就可以放任何的子类进去,在这个过程中就发生了里氏转换。
//public static String Join(String? separator, params String?[] value);
Console.WriteLine(string.Join("|", new string[] { "1", "2", "3" }));
类型转换判断
is
is检查一个对象是否强转为目标类型,若能强转返回True,否则返回False。
is操作符永远不会抛异常
class Program
{
static void Main(string[] args)
{
Person p = new Student();
if(p is Student)
{
Console.WriteLine("能够强转为Student类");
}
if(p is Teacher)
{
Console.WriteLine("能够强转为Teacher类");
}
else
{
Console.WriteLine("不能够强转为Teacher类");
}
Console.ReadKey();
}
}
public class Person
{
public void SayPerson()
{
Console.WriteLine("我是Person类方法");
}
}
public class Student:Person
{
public void SayStudent()
{
Console.WriteLine("我是Person类方法");
}
}
public class Teacher : Person
{
public void SayTeacher()
{
Console.WriteLine("我是Person类方法");
}
}

as
as表示类型转换,能给转换为目标类型,那么返回改目标类型的对象,否则返回一个空
class Program
{
static void Main(string[] args)
{
Person p = new Student();
Student s1 = p as Student;
s1.SayStudent();
Console.ReadKey();
}
}
public class Person
{
public void SayPerson()
{
Console.WriteLine("我是Person类方法");
}
}
public class Student:Person
{
public void SayStudent()
{
Console.WriteLine("我是Person类方法");
}
}
public class Teacher : Person
{
public void SayTeacher()
{
Console.WriteLine("我是Person类方法");
}
}
