在C#的类当中,有子类与父类两个概念,其中子类可以使用父类的属性和字段,称为继承。
问1:子类对象与父类对象能否相互调用?
using System;
namespace _0530里氏转换
{
class Program
{
static void Main(string[] args)
{
person a = new person();
student b = new student();
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
}
}
现在我们在主函数中使用对象来调用成员,如图。
可以发现,子类对象能够使用父类中的成员,而父类对象无法使用之类的的成员。
那么,如何通过父类对象来使用子类中的成员呢?
一:里氏转换
1)子类可以赋值给父类对象。
static void Main(string[] args)
{
person a = new student();
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
2)如果一个父类中装的是子类对象,那么可以将这个父类强制转换为子类
static void Main(string[] args)
{
person a = new student();
student b = (student)a;
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
这样的代码是行得通的。
二:is和as
1)is类型转换。
作用:表示类型转换,如果能够转换成功,则返回true,否则返回false。
使用:
class Program
{
static void Main(string[] args)
{
person a = new student();
if (a is student)
{
student b = (student)a;
b.shello();
}
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
解析:可以看到代码中一开始先创建了一个父类对象a,但将子类类型赋值给了他,在if语句中,使用了is判断其是否可转换为子类,若可转换的话,则会执行子类中的方法,输出“你好,我是小刘”,现在让我们来看看运行结果吧。
如图:
接下来我们看看错误示范,看代码。
class Program
{
static void Main(string[] args)
{
person a = new student();
if (a is doctor)
{
doctor b = (doctor)a;
b.dhello();
}
else
Console.WriteLine("转换失败");
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
class doctor : person
{
public void dhello()
{
Console.WriteLine("你好,我是小王");
}
}
在主函数中可以看到,父类对象a中装的是子类student,并不是doctor,那么让我们看看运行结果是怎样的吧。
运行结果:
is的基本使用就是这样的了,具体用法需要大家自己上机进行使用,接下来看看as的用法吧。
2)as类型转换
作用:如果能够转换成功,则直接返回转换后的对象,否则返回null。
使用:
class Program
{
static void Main(string[] args)
{
person a = new student();
(a as student).shello();
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
}
解析:与is代码相似,唯一不同的是if语言换成了(a as student).shello();这条语句的意思就可根据as的特点来运行,若能转换成功,则a as student就相当于一个子类对象new student(),随后的.shello(),则是调用子类中的方法,若转换成功,则会输出“你好,我是小刘”,现在一起来看看运行结果吧。
运行结果:
一样来看看错误示范吧!
代码:
class Program
{
static void Main(string[] args)
{
person a = new student();
(a as doctor).dhello();
}
class person
{
public void phello()
{
Console.WriteLine("你好,我是小明");
}
}
class student:person
{
public void shello()
{
Console.WriteLine("你好,我是小刘");
}
}
class doctor : person
{
public void dhello()
{
Console.WriteLine("你好,我是小王");
}
}
大家不妨根据as的特点想想会运行出什么结果呢?是无法运行呢还是输出空呢,接下来来看看运行结果,是不是跟你想的一样。
运行结果:
可以看到,因为是个空值,所以程序在执行到这的时候抛出了异常。
总结:以上就是我学习里氏转换的一点心得,但这两个类型转换还是需要多加练习才能掌握。