功能:自定义一个怪物类
Monster类
using System;
using System.Collections.Generic;
using System.Text;
namespace _05自定义一个类
{
public class Monster
{
private string mName;
private int mLevel;
private int mHp;
private int mAttack;
private int mDefence;
public string Name {
set { this.mName = value; }
get { return this.mName; }
}
public int Level
{
set { this.mLevel = value; }
get {
if (this.mLevel < 1)
return 1;
if (this.mLevel > 100)
return 100;
return this.mLevel;
}
}
public int Hp
{
set { this.mHp = value; }
get {
if (this.mHp < 0) {
this.mHp = 0;
Console.WriteLine("我已阵亡"); }
if (this.Hp > 100) {
this.mHp = 100;
Console.WriteLine("我已无敌");}
return this.mHp; }
}
public int Attack
{
set { this.mAttack = value; }
get { return this.mAttack; }
}
public int Defence
{
set { this.mDefence = value; }
get {
if (this.mDefence < 0)
return 0;
return this.mDefence; }
}
// 自定义攻击方法
public void AttackAction()
{
Console.WriteLine("我是怪物{0},我的等级是{4},我的血量是{1},我的攻击力是{2},我的防御力是{3}", this.mName, this.mHp, this.mAttack, this.mDefence, this.mLevel);
}
// 自定义受攻击方法
public void DamageAction(int hp)
{
this.mHp -= hp;
Console.WriteLine("我被攻击了,我现在的生命值是{0}", this.mHp);
}
// 构造方法
public Monster() { }
// 重写方法
public Monster(string _name, int _hp, int _attack, int _defence) {
this.Name = _name;
this.Hp = _hp;
this.Attack = _attack;
this.Defence = _defence;
}
}
}
主函数:
using System;
namespace _05自定义一个类
{
class Program
{
static void Main(string[] args)
{
// 自定义一个类
Monster a = new Monster("剑圣",100,40,30);
// 调用类方法
a.AttackAction();
a.DamageAction(10);
}
}
}
效果: