摘要
枚举enum常规使用方法。获取枚举值(枚举常量),获取枚举值对应的名称,获取枚举值的个数,判断枚举值或名称是否存在。建立枚举值和枚举值排列顺序的关系。
//枚举类型
enum enumTest
{
A = 0,
B = 1,
}
获取枚举值
第一种经常使用。第二、三、四种,根据名称获取对应的枚举值。第五中遍历。
第一种
int nNum = (int)enumTest.A;
第二种
//传入名称
string str = "A";
int nNum = (int)Enum.Parse(typeof(enumTest), str);
第三种
//传入名称
string str = "A";
enumTest enumGet = (enumTest)Enum.Parse(typeof(enumTest), str);
int nNum = (int)enumGet;
第四种
//传入名称
string str = "A";
enumTest enumGet;
if (Enum.TryParse(str, out enumGet))
{
int nNum = (int)enumGet;
}
第五种
//遍历
foreach (var value in Enum.GetValues(typeof(enumTest)))
{
int nNum = (int)value;
}
获取名称
第一种经常使用。第二、三、六种,根据枚举值获取对应的名称。第四中遍历。第五种获取数组。
第一种
string str = enumTest.A.ToString();
第二种
//传入枚举值
int index = 0;
string str = Enum.GetName(typeof(enumTest), index);
第三种
//传入枚举值
int index = 0;
enumTest enumGet = (enumTest)Enum.Parse(typeof(enumTest), index.ToString());
string str = enumGet.ToString();
第四种
//遍历
foreach (var value in Enum.GetValues(typeof(enumTest)))
{
string str = ((enumTest)value).ToString();
}
第五种
//数组
string[] strArr = Enum.GetNames(typeof(enumTest));
第六种
//传入枚举值
int index = 0;
enumTest enumGet;
if (Enum.TryParse(index.ToString(), out enumGet))
{
if (Enum.IsDefined(typeof(enumTest), enumGet.ToString()))
{
string str = enumGet.ToString();
}
}
获取枚举值的个数
第一、二种类似。
第一种
int length = Enum.GetNames(typeof(enumTest)).Length;
第二种
int length = Enum.GetValues(typeof(enumTest)).Length;
判断枚举值或名称是否存在
第一、二种类似。
第一种
//传入枚举值
index = 0;
bool result = Enum.IsDefined(typeof(enumTest), index);
第二种
//传入名称
string str = "A";
bool result = Enum.IsDefined(typeof(enumTest), str);
根据枚举值获取枚举值排列顺序
public static bool GetIndex(int Value, out int Index)
{
bool reslut = true;
int index = 0;
Dictionary<int, int> dic = new Dictionary<int, int>();
int i = 0;
foreach (enumTest Value in Enum.GetValues(typeof(enumTest)))
{
int ret = (int)Enum.Parse(typeof(enumTest), Value.ToString());
dic.Add(i, ret);
if (ret == Value)
{
index = i;
}
i++;
}
int value;
bool b = dic.TryGetValue(index, out value);
if (!b || value != Value)
{
reslut = false;
}
Index = index;
return reslut;
}
根据枚举值排列顺序获取枚举值
public static bool GetValue(int Index, out int Value)
{
bool reslut = true;
Dictionary<int, int> dic = new Dictionary<int, int>();
int i = 0;
foreach (enumTest Value in Enum.GetValues(typeof(enumTest)))
{
int ret = (int)Enum.Parse(typeof(enumTest), Value.ToString());
dic.Add(i, ret);
i++;
}
bool b = dic.TryGetValue(Index, out Value);
if (!b)
{
reslut = false;
}
return reslut;
}