天天看點

Enum與string、int的轉換

以下面枚舉為例:

public enum Mode
{
    Study,
    Examination
}
           

1、enum轉String

Enum.GetName(typeof(Mode), Mode.Study);
           

或者采用ToString方法:Mode.Study.ToString();

2、string轉enum

mode = (Mode)Enum.Parse(typeof(Mode), "Study", false);
           

ignoreCase值設定了false,是指是否忽略大小寫

3、enum轉int

enum轉int采用int強轉的方法:(int)Mode.Study;

4、int轉enum

(Mode)Enum.ToObject(typeof(Mode), 1);
           

同樣,也可以強轉:(Mode)1;