簡體   English   中英

如何在 switch 語句中使用枚舉 [Unity c#]

[英]How can I use Enum in switch statement [Unity c#]

我要做的是檢測“項目”的類型並在 switch 語句中使用它,並在此基礎上選擇正確的設備插槽。 我的代碼:

    public EquipmentSlot WeaponSlot;
    public EquipmentSlot ChestplateSlot;
    public EquipmentSlot LeggingsSlot;
    public EquipmentSlot HelmetSlot;

    public void EquipItem(Item item)
    {
        EquipmentSlot chosenSlot = null;
        
        switch(item.type)
        {
            case item.type.weapon:
                chosenSlot = WeaponSlot;
                break;
            case item.type.chestplate:
                chosenSlot = ChestplateSlot;
                break;
            case item.type.leggings:
                chosenSlot = LeggingsSlot;
                break;
            case item.type.helmet:
                chosenSlot = HelmetSlot;
                break;
        }

        chosenSlot.EquippedItem = item;
    }

項目 class:

    public enum Type
    {
        weapon,
        chestplate,
        leggings,
        helmet
    }
    public Type type;

出現此錯誤:錯誤 CS0176:無法使用實例引用訪問成員“Item.Type.helmet”; 改為使用類型名稱來限定它(switch 中每種情況四次)

而不是case item.type.weapon:應該是case Type.weapon:

嘗試這個

switch (item.type)
    {
        case Type.weapon:
            chosenSlot = WeaponSlot;
            break;
        case Type.chestplate:
            chosenSlot = ChestplateSlot;
            break;

        .....
    }

但是,例如,如果將 Type 重命名為 ArmoryType,它將更具可讀性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM