C# 基础 - Enum 的一些操作
1. int 转换成 enum
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
Suit spades = (Suit)0;
Suit hearts = Enum.Parse(typeof(Suit), "1");
Suit tryClubs;
Enum.TryParse<Suit>("2", out tryClubs);
Suit diamonds = (Suit)Enum.ToObject(typeof(Suit), 3);
- 茴字有几种写法并不重要;
- 安全的情况下直接用 Enum.Parse(Type enumType, string value);
- 需要确认的情况下用 Enum.TryParse
(string value, out TEnum result)。
2. enumerate 之
foreach (Suit suit in Enum.GetValues(typeof(Suit))) //Array
{
Console.WriteLine(suit);
}
Console.WriteLine();
List<int> indexList = new List<int>() { 1, 2 };
foreach (Suit suit in indexList.Cast<Suit>()) //Array
{
Console.WriteLine(suit);
}
outputs:
Spades
Hearts
Clubs
Diamonds
Hearts
Clubs