如何在c#中将枚举值名称返回给属性

时间:2016-08-05 05:27:42

标签: c# json unity3d

首先,我是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()));
          }
     }
}

// card [i] [“C_TYPE”]。ToString() 它说无法从字符串转换为CARDS.ClassType

2 个答案:

答案 0 :(得分:0)

怎么样:

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

答案 1 :(得分:0)

枚举值上的ToString()返回枚举的字符串值。还可以为枚举值返回自定义字符串值,请检查这些链接,link1link2

示例:

ClassType.Warrior.ToString();

ctype.ToString();