忽然笑
这是我将采用的方法:设置有效攻击的列表,然后简单地与该列表进行比较。试试这个:var validAttacks = new (UnitType, AttackType)[]{ (UnitType.Air, AttackType.Air), (UnitType.Air, AttackType.Ground), (UnitType.Ground, AttackType.Ground), (UnitType.Water, AttackType.Water), (UnitType.Water, AttackType.Air),};使用这种列表,您可以创建您喜欢的任何组合。您甚至可以在运行时设置它以使其灵活。现在,要使用它,只需执行以下操作:var unit = UnitType.Water;var attack = AttackType.Air;var attackable = validAttacks.Contains((unit, attack));Console.WriteLine(attackable);这会产生True因为该组合的UnitType.Water和AttackType.Air是在列表中。现在,你可以更进一步,设置这种事情:public class Unit{ private Dictionary<(UnitType, AttackType), Action<Unit, Unit>> _validAttacks; public Unit() { _validAttacks = new Dictionary<(UnitType, AttackType), Action<Unit, Unit>>() { { (UnitType.Air, AttackType.Air), (s, o) => MissleAttack(s, o) }, { (UnitType.Air, AttackType.Ground), (s, o) => MissleAttack(s, o) }, { (UnitType.Ground, AttackType.Ground), (s, o) => TankAttack(s, o) }, { (UnitType.Water, AttackType.Water), (s, o) => TorpedoAttack(s, o) }, { (UnitType.Water, AttackType.Air), (s, o) => IcbmAttack(s, o) }, }; } public UnitType unitType; public AttackType attackType; void OnTriggerEnter(Collider other) { Unit unit = other.GetComponent<Unit>(); if (_validAttacks.ContainsKey((unit.unitType, attackType))) { _validAttacks[(unit.unitType, attackType)].Invoke(this, unit); } } public void TankAttack(Unit self, Unit other) { ... } public void MissleAttack(Unit self, Unit other) { ... } public void TorpedoAttack(Unit self, Unit other) { ... } public void IcbmAttack(Unit self, Unit other) { ... }}现在我可以合并一个与(UnitType, AttackType). 代码变得非常简洁明了。