Unity C# basic review 11 - interface collaboration (P287)

interface IWeapon 
{
    int Atk { get; set; }
}
class Sword : IWeapon
{
    int atk;

    public Sword(int atk)
    {
        this.atk = atk;
    }

    public int Atk
    {
        get => atk;
        set => atk = value;
    }
}
class Role 
{
    //攻击力
    int atk;
    //武器接口
    IWeapon weapon;
    public Role()
    {
        this.atk = 100;
    }

    public int Atk { get => atk;  }
    internal IWeapon Weapon { get => weapon; set => weapon = value; }

    public void Attack()
    {
        //计算玩家的攻击值
        //自身攻击+装备加成
        int hurt = this.atk + weapon.Atk;
        Debug.Log("产生了" + hurt.ToString() + "伤害");
    }
}
public class program : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Role r = new Role();
        r.Weapon = new Sword(1000);
        r.Attack();
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/123048283