如何将枚举值名称返回到c#中的属性

本文关键字:属性 返回 枚举 | 更新日期: 2023-09-27 18:00:14

首先,我是c#中的一个开头。我正在尝试编写一些游戏代码。我不知道如何将枚举值作为字符串返回。

这是我的密码。

public class CARDS {
    public CARDS(int id, int atk, ClassType ctype, string name) {
        this.CARD_ID = id;
        this.C_TYPE = ctype;
        this.ATK = atk;
        this.NAME_EN = name;
    }
     public CARDS() {
          this.CARD_ID = -1;
     }
     public int CARD_ID { get; set; }   
     public ClassType C_TYPE { get; set; }
     public int ATK { get; set; }
     public string NAME_EN { get; set; }
     public enum ClassType {
          Warrior,
          Mage,
          Archer,
          Thief,
          Bishop,
          Monk,
          Guardian,
          Destroyer,
          Chaser,
          Hermit,
          Alchemy   
     }
}

我试着这么做。

public class CardCollection : MonoBehaviour {
     private List<CARDS> dbase = new List<CARDS>();
     private JsonData cardsdata;
     private JsonData card;
     void Start() {
          cardsdata = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/Json/card.json"));
          ConstructCardData();
          Debug.Log(dbase[1].NAME_EN + " " + dbase[23].NAME_EN);
     }
     void ConstructCardData() {
          card = cardsdata["CARDS"];
          for (int i = 0; i < card.Count; i++) {
               dbase.Add(new CARDS((int)card[i]["CARD_ID"], (int)card[i]["ATK"], card[i]["C_TYPE"].ToString(), card[i]["NAME_EN"].ToString()));
          }
     }
}

//卡片[i]["C_TYPE"]。ToString()它说不能从字符串转换成卡片。ClassType

如何将枚举值名称返回到c#中的属性

关于:

public class CARDS
{
    public CARDS(int id, int atk, ClassType ctype, string name)
    {
        this.CARD_ID = id;
        this.C_TYPE = Enum.GetName(ctype.GetType(), ctype); //Use Enum.GetName to get string
        this.ATK = atk;
        this.NAME_EN = name;
    }
    public CARDS()
    {
        this.CARD_ID = -1;
    }
    public int CARD_ID { get; set; }
    public string C_TYPE { get; set; } //change type to string
    public int ATK { get; set; }
    public string NAME_EN { get; set; }
    public enum ClassType
    {
        Warrior,
        Mage,
        Archer,
        Thief,
        Bishop,
        Monk,
        Guardian,
        Destroyer,
        Chaser,
        Hermit,
        Alchemy
    }
}
枚举值上的

ToString()返回枚举的字符串值。也可以为枚举值返回自定义字符串值,检查这些链接,链接1,链接2

示例:

ClassType.Warrior.ToString();
ctype.ToString();