本文介绍如何遍历枚举中的所有成员,并提供枚举名称、枚举值以及枚举名称的字符串形式间的互相转化方法。
有如下枚举类型:
public enum EnumBookType : byte
{
Unknown,
Science,
History
}
IDictionary〈string, byte〉 booktype = new Dictionary〈string, byte〉();
string[] t = Enum.GetNames(typeof(EnumBookType));
foreach(string f in t)
{
byte d = (byte)Enum.Parse(typeof(EnumBookType), f);
booktype.Add(f, d);
}
如果要获取字符串“Science”的枚举值,则可以用 (byte)Enum.Parse(typeof(EnumBookType), "Science") 获得;
如要获得 Science 的枚举值,则直接使用 (byte)EnumBookType.Science;
如要获得 2 的枚举名称,则直接使用 (EnumBookType)2。