2014-02-23 85 views
7

我不知道这是否可行,但我正在使用XNA和C#编写一个简单的游戏,并且需要某种特定变量来处理更多不止一种枚举类型。你控制的角色都有一个库存插槽,可以低于水果类型之一:如何在一个变量中处理多个枚举类型

public enum Fruit : int {Apple, Banana, Orange}; 
public Fruit carrying; 

但字符也可以是能够携带别的东西:

public enum Misc : int {Parcel, Brush}; 

我不想要将它们全部合并为一个枚举,因为我希望Fruit枚举不同,并且我不想有两个不同的“携带”变量 - 一个用于Fruit,一个用于杂项。

有没有什么方法可以将超级枚举合并为所有五个成员的第三枚枚举?

编辑:谢谢你的回应。我决定创建一个单一的Item类型(其中的一个成员是区分Fruit和Misc的枚举),并通过XML将它们加载到列表中。

回答

7

这听起来像你可能想为CarriableItem或类似的工会类型。例如:

public sealed class CarriableItem 
{ 
    public Fruit? Fruit { get; private set; } 
    public Misc? Misc { get; private set; } 

    // Only instantiated through factory methods 
    private CarriableItem() {} 

    public static CarriableItem FromFruit(Fruit fruit) 
    { 
     return new CarriableItem { Fruit = fruit }; 
    } 

    public static CarriableItem FromMisc(Misc misc) 
    { 
     return new CarriableItem { Misc = misc }; 
    } 
} 

你可能然后希望再枚举,表示正在开展哪些项目种类:

public enum CarriableItemType 
{ 
    Fruit, 
    Misc 
} 

属性然后添加到CarriableItem

public CarriableItemType { get; private set; } 

并在工厂方法中适当地设置它。

然后你的人将只有一个变量CarriableItem类型。

0

为什么限制自己到一个枚举?如果你有一个界面和它的各种实现,你可以自定义你的项目的行为!

// generic item. It has a description and can be traded 
public interface IItem { 
    string Description { get; } 
    float Cost { get; } 
} 

// potions, fruits etc., they have effects such as 
// +10 health, -5 fatigue and so on 
public interface IConsumableItem: IItem { 
    void ApplyEffect(Character p); 
} 

// tools like hammers, sticks, swords ect., they can 
// be used on anything the player clicks on 
public interface IToolItem: IItem { 
    void Use(Entity e); 
}  

这将使您的代码更易于使用枚举来区分不同的项目。如果您仍需要这样做,您可以利用is运营商和方法IEnumerable.OfType。所以你可以这样做:

public class HealthPotion: IConsumableItem { 
    public string Description { 
     get { return "An apple you picked from a tree. It makes you feel better."; } 
    } 

    public float Cost { 
     get { return 5f; } 
    } 

    public void ApplyEffect(Character p) { 
     p.Health += 1; 
    } 
} 

public class Player: Character { 
    public List<IItem> Inventory { get; private set; } 

    private IEnumerable<IConsumableItem> _consumables { 
     get { return this.Inventory.OfType<IConsumableItem>(); } 
    } 

    public void InventoryItemSelected(IItem i) { 
     if(IItem is IConsumableItem) { 
      (IItem as IConsumableItem).ApplyEffect(this); 
     } 
     else if(IItem is IToolItem) { 
      // ask the player to click on something 
     } 
     else if /* ...... */ 

     this.Inventory.Remove(i); 
    } 
} 
相关问题