2014-02-23 2 views
7

이것이 가능한지는 모르겠지만 XNA와 C#을 사용하여 간단한 게임을 작성하고 있으며 더 많은 것을 처리 할 수있는 특정 변수가 필요합니다. 하나의 열거 유형보다하나의 변수에서 여러 열거 형을 처리하는 방법

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

그러나 문자는 다른 것을 수행 할 수 있습니다 :

public enum Misc : int {Parcel, Brush}; 

을 내가하지가 제어 문자는 아래의 과일 유형 중 하나가 될 수있는 하나의 인벤토리 슬롯을 가지고 있습니다 과일 열거 형을 구별하기를 원하기 때문에 이들을 모두 하나의 열거 형으로 병합하고 싶습니다. 과일 및 기타 용의 두 가지 '운반'변수를 갖고 싶지는 않습니다.

슈퍼 열거 형을 사용하여 5 명의 구성원 모두의 세 번째 열거로 병합 할 수있는 방법이 있습니까?

편집 : 답변 해 주셔서 감사합니다. 필자는 하나의 Item 유형 (Fruit과 Misc를 구별하는 열거 형의 멤버 임)을 작성하여 XML을 통해 List에로드하기로 결정했습니다.

답변

7

CarriableItem 또는 이와 비슷한 형식의 공용 구조체가 필요하다고 생각됩니다. 예를 들어 :

public enum CarriableItemType 
{ 
    Fruit, 
    Misc 
} 

그런 다음 CarriableItem에 속성을 추가 :

public CarriableItemType { get; private set; } 

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 }; 
    } 
} 

당신은 또한 다음 수행되는 아이템의 종류를 표시하기 위해 다른 열거 할 수 있습니다 팩토리 메소드에서 적절하게 설정하십시오.

그러면 사람은 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); 
    } 
} 
관련 문제