-
枚举
例如有一个动物枚举
public enum AnimalEnum { Dog =12, Cat = 10 }
- Enum Convert To String
public void ConvertToString(AnimalEnum animal)
{
animal.ToString();//Example: animal == AnimalEnum.Dog => "Dog"
}
- Enum To Int
public void ConvertToInt(AnimalEnum animal) { int i = (int)animal;//Example: animal == AnimalEnum.Dog => 12 }
- 遍历枚举(反射 + Enum.GetNames())
- 字符串格式
public void Enumerate() { Type type = typeof(AnimalEnum); string[] names = Enum.GetNames(type); foreach (string str in names) { Console.WriteLine(str); } }
- 枚举格式
public void Enumerate() { Array array = Enum.GetValues(typeof(AnimalEnum)); foreach (AnimalEnum ae in array) { Console.WriteLine(ae.ToString()); } }
- Enum.Fotmat 格式化输出
public static string Format( Type enumType, Object value, string format )
Enum.Format(typeof(AnimalEnum),AnimalEnum.Dog,format);
- Format
- d or D 十进制输出
- x or X 十六进制输出
- g or G 字符串格式输出
- f or F 字符串格式输出
判断枚举是否定义
public bool IsDefined(int num) { return Enum.IsDefined(typeof(AnimalEnum),num); } public bool IsDefined(string name) { return Enum.IsDefined(typeof(AnimalEnum),num); }