.Net C# 枚举
1.枚举的概念
枚举的定义罗列出了所有可能的取值,枚举变量的值只能是罗列出的值之一,例如:
public enum FormStatus
{
WaitApprove,Approved,Reject
}
{
WaitApprove,Approved,Reject
}
枚举元素的默认基础类型为 int。默认情况下,第一个枚举数的值为 0,后面每个枚举数的值依次递增 1。也可以自己定义枚举的值:
public enum FormStatus
{
WaitApprove = 100,
Approved = 200,
Reject = 300
}
{
WaitApprove = 100,
Approved = 200,
Reject = 300
}
2.枚举的使用
代码
FormStatus fs = FormStatus.WaitApprove;
//Enum 转 Int
int fsValue = (int)fs;
Console.WriteLine(fsValue);
//int 转Enum
fs = (FormStatus)1;
Console.WriteLine(fs);
//判断枚举值
if(fs.Equals(FormStatus.Approved))
{
Console.WriteLine("该单据已经被签核!");
}
//遍历所有的值
Type fsType = typeof(FormStatus);
Console.WriteLine("The status of the Form, and their corresponding values are:");
foreach (string s in Enum.GetNames(fsType) )
Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( fsType, Enum.Parse(fsType, s),"d"));
Console.ReadLine();
//Enum 转 Int
int fsValue = (int)fs;
Console.WriteLine(fsValue);
//int 转Enum
fs = (FormStatus)1;
Console.WriteLine(fs);
//判断枚举值
if(fs.Equals(FormStatus.Approved))
{
Console.WriteLine("该单据已经被签核!");
}
//遍历所有的值
Type fsType = typeof(FormStatus);
Console.WriteLine("The status of the Form, and their corresponding values are:");
foreach (string s in Enum.GetNames(fsType) )
Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( fsType, Enum.Parse(fsType, s),"d"));
Console.ReadLine();