直接上代码:
using UnityEngine;
/// <summary>
///
/// * Writer:June
///
/// * Date: 2021.1.30
///
/// * Function:重载内置运算符
///
/// * Remarks:可以重载除赋值号以外的符号运算
///
/// </summary>
public class OperatorTest : MonoBehaviour
{
private void Start()
{
Hero hero1 = new Hero()
{
HP = 100,
Attack = 200
};
Hero hero2 = new Hero()
{
HP = 500,
Attack = 20
};
Debug.LogFormat("两个不同实例做加法:\n 血量:{0} , 攻击力:{1}", (hero1 + hero2).HP, (hero1 + hero2).Attack);
}
}
class Hero
{
public int HP { get; set; }
public int Attack { get; set; }
public static Hero operator -(Hero _hero1, Hero _hero2)
{
return new Hero
{
HP = _hero1.HP - _hero2.HP,
Attack = _hero1.Attack - _hero2.Attack
};
}
public static Hero operator +(Hero _hero1, Hero _hero2)
{
return new Hero
{
HP = _hero1.HP + _hero2.HP,
Attack = _hero1.Attack + _hero2.Attack
};
}
}
运行结果: