3

我需要让玩家装备一件物品,如下所示:

IEquiptable是一个接口。

这个方法在我的player课堂上。

public void equip(IEquiptable equipable) 
    {
        switch (equipable.GetType())
        {
            case equipable is Weapons:
                this.weapon = equipable;
                break;

            case equipable is Shield:
                this.shield = equipable
                break;

                //etc etc..
        }
    }

我收到一个错误,即 switch experession 必须是 bool、char、string、integral、enum 或相应的可为空类型。

我可以通过在我的每个武器/盾牌等类中使用一个 equit 方法并将我的player类作为参数传递来处理它。但我觉得这有点不合逻辑,因为玩家应该装备一件物品,而不是一件物品将它自己装备在玩家身上。

4

3 回答 3

3

你已经有了一个接口,为什么不使用它呢?

public interface IEquipable
{
    void EquipOn( Player player );
}

public class Shield : IEquipable
{
    public void EquipOn( Player player )
    {
        player.shield = this;
    }
}

public class Weapons : IEquipable
{
    public void EquipOn( Player player )
    {
        player.weapon = this;
    }
}

你的代码变成

public void equip(IEquiptable equipable) 
{
   equipable.EquipOn( this ); 
}

事实上,您甚至不需要此方法,因为它已被简化为仅将其工作转发给适当的类。每次你有你的时候IEquipable,你只需调用它的EquipOn方法。

于 2013-10-06T17:47:15.557 回答
1
public void equip(IEquiptable equipable) 
{
   var type = equipable.GetType();
   if(type is Weapons)
   {
    this.weapon = equipable;
    return;
   }
   if(type is Shield)
   {
     this.shield = equipable;
     return;
   }
   //etc
}
于 2013-10-06T17:42:05.270 回答
0

由于case的值必须是常量,因此传统的解决方案是创建一个enum ..

public enum EquippableTypes {
    Weapons,
    Shield,
    Antenna,
    Underwear
}

public partial class Player {
    public void Equip(IEquippable equippable) {
        switch(equippable.Type) {
            case EquippableTypes.Weapons:
                this.weapon=equippable;
                break;

            case EquippableTypes.Shield:
                this.shield=equippable;
                break;

            case EquippableTypes.Antenna:
                this.antenna=equippable;
                break;

            case EquippableTypes.Underwear:
                this.underwear=equippable;
                break;

            // ... 
        }
    }

    IEquippable weapon, shield, antenna, underwear;
}

所以你的可装备接口/类看起来像那样..

public partial interface IEquippable {
    EquippableTypes Type {
        get;
    }
}

public partial class Weapons: IEquippable {
    public EquippableTypes Type {
        get {
            return EquippableTypes.Weapons;
        }
    }
}

public partial class Shield: IEquippable {
    public EquippableTypes Type {
        get {
            return EquippableTypes.Shield;
        }
    }
}

public partial class Antenna: IEquippable {
    public EquippableTypes Type {
        get {
            return EquippableTypes.Antenna;
        }
    }
}

public partial class Underwear: IEquippable {
    public EquippableTypes Type {
        get {
            return EquippableTypes.Underwear;
        }
    }
}
于 2013-10-06T18:29:07.433 回答