里氏转换----基本的转换方式
using System;
namespace 里氏转换
{
class MainClass
{
public static void Main(string[] args)
{
//子类对象可以赋值给父类对象。 父类如果装入的是子类,那父类类型可以强转为子类
Father F = new Son();
//如果一个地方需要一个父类作为参数,我们可以传入子类代替
//强转
Son S = (Son)F;
S.S_S();
is 语法的使用
//is 类型转换语法 转换成功 返回true 失败FALSE
//改进语法
Father FF = new Son();//父类包含子类
if ( FF is Son) //如果父类可以转为子类的话
{
Son SF = (Son)F;
Console.WriteLine("转换成功");
}
else
{
Console.WriteLine("转换失败.");
}
as语法的使用
//as语法 转换成功则返回对应的对象,否则返回 NULL
Console.WriteLine("_________________");
Father FFF = new Son();//父类包含子类son
Brother B = FFF as Brother;//但父类不包含子类Brother
Type ty = B.GetType();
//引发NULL 异常
}
}
替换为下面的代码
Console.WriteLine("_________________");
Father FFF = new Son();//父类包含子类
Son SSS = FFF as Son;
Type ty = SSS.GetType();
Console.WriteLine(ty);
//打印结果
//里氏转换.Son
public class Father
{
public void F_S()
{
Console.WriteLine("Father");
}
}
public class Son:Father
{
public void S_S()
{
Console.WriteLine("Son");
}
}
public class Brother:Father
{
public void B_s()
{
Console.WriteLine("Brother");
}
}
}
完整code