好久都没有写了。今天做了类继承的练习,做了一个小队,进行简单的判定。

namespace 兵团建立练习
{
class ServantBasics
{
public string name; //protected 代表着子类可以继承,外部不能调用
protected int attack; public ServantBasics(string name,int attack) //做了一个构造函数,用于赋值
{
this.name = name;
this.attack = attack;
}
} class SaberServant : ServantBasics //用于继承父类函数 这个就是语法
{
public SaberServant(string name, int attack) : base(name, attack) //这个其实是上面输入父类后,然后有个红线自动点击会自动填入,不过我也认真记了一下,和this用法挺像的
{
} public void skill()
{
Console.WriteLine("“EX咖喱棒!!!”");
Console.WriteLine("给对面造成了{0}点伤害",attack); }
} class ArcherServant: ServantBasics //用于继承父类函数
{
public ArcherServant(string name,int attack) : base(name,attack)
{
} public void skill()
{
Console.WriteLine("“无限剑制”");
Console.WriteLine("给对面造成了{0}点伤害", attack);
}
}
class RiderServant : ServantBasics //用于继承父类函数
{
public RiderServant(string name, int attack) : base(name, attack)
{
} public void skill()
{
Console.WriteLine("“无限剑制”");
Console.WriteLine("给对面造成了{0}点伤害", attack);
}
}
class CasterServant : ServantBasics //用于继承父类函数
{
public CasterServant(string name, int attack) : base(name, attack)
{
} public void skill()
{
Console.WriteLine("“万符必应破戒”");
Console.WriteLine("给对面造成了{0}点伤害", attack);
}
} class Program
{
static void Main(string[] args)
{
var r = new Random(); //建立一个随机的骰子
var servantParty = new ServantBasics[]; //建立了一个10个人小队的数组
for (int i = ; i < servantParty.Length; i++)
{
var roll = r.Next(, );
if (roll > )
{
servantParty[i] = new SaberServant("剑士",);
}
else if (roll > )
{
servantParty[i] = new ArcherServant("弓箭手", );
}
else
{
servantParty[i] = new CasterServant("魔法师", );
}
} for (int i = ; i < servantParty.Length; i++)
{
if (servantParty[i] is SaberServant) //我是这样理解的,用父类创建的这个子类,是不是SaberSevrvant
{
SaberServant saber = servantParty[i] as SaberServant; //如果不是返回空,如果是就给saber赋值
Console.WriteLine("这是第{0}个,职业是{1}",i+,saber.name);
saber.skill();
}
else if (servantParty[i] is ArcherServant)
{
Console.WriteLine("这是第{0}个,职业是{1}", i + , (servantParty[i] as ArcherServant).name);
(servantParty[i] as ArcherServant).skill(); //尝试进行简写
}
else
{
Console.WriteLine("这是第{0}个,职业是{1}", i + , (servantParty[i] as CasterServant).name);
(servantParty[i] as CasterServant).skill();
//我自己测试发现不能直接用servantParty[i].skill,没有选项,因为这个数组是基于父类建立的
//这种方法被称为里氏转换,挺神奇的,因为我以为数组都存好了数据new后的数据,居然不能 .skill
}
} Console.ReadKey(); }
}
}

用了一个数组来记录东西,我觉得这样似乎可以做生成地图随机怪兽的玩意,所以记录下来,方便以后忘记时候来看看,可能会有帮助

05-11 13:52