父类容器装子类对象
方便进行对象存储和管理
is 和 as
is 判断一个对象是否为指定类对象
返回值bool
as 将一个对象转化为制定类对象
成功返回执行类型对象,失败返回null
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text.Json.Serialization;
class Weapon
{
}
class SubmachineGun : Weapon
{
public void Atk()
{
Console.WriteLine("冲锋抢");
}
}
class ShotGun : Weapon
{
public void Atk()
{
Console.WriteLine("散弹枪");
}
}
class Pistol : Weapon
{
public void Atk()
{
Console.WriteLine("手枪");
}
}
class Dagger : Weapon
{
public void Atk()
{
Console.WriteLine("匕首");
}
}
class Player
{
public Weapon nowHaveWeapon;
public Player()
{
nowHaveWeapon=new Dagger();
}
public void Pickup(Weapon weapon )
{
nowHaveWeapon = weapon;
}
}
class Program
{
static void Main()
{
Player player = new Player();
ShotGun shotGun = new ShotGun();
(player.nowHaveWeapon as Dagger).Atk();
player.Pickup(shotGun);
(player.nowHaveWeapon as ShotGun).Atk();
}
}