C# 面向对象04 自定义一个类

 功能:自定义一个怪物类

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);
        }
    }
}

效果:

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值