01.定义
public enum State
{
One=10,
Two=50,
Three
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(System.Enum.IsDefined(typeof(State), State.One)); //true
Console.WriteLine(System.Enum.IsDefined(typeof(State),60)); //false
Console.ReadKey();
}
}
public enum State:byte
{
One,
Two=50,
Three,
Other=Three,
Four,
}
class Program
{
static void Main(string[] args)
{
//One是第一个枚举默认为0
Console.WriteLine((int)State.One); //0
//Two被显式的赋值为50所以他后面的Three会被赋值为51
Console.WriteLine((int)State.Three); //51
//Other的值赋值为51(将Three的值赋给Other)
Console.WriteLine((int)State.Other); //51
Console.ReadKey();
}
}
04.
05.枚举之间的转换
public enum ConnectionState1
{
One,
Two,
Three
}
public enum ConnectionState2
{
One,
Two,
Three,
}
class Program
{
static void Main(string[] args)
{
ConnectionState1[] state1s=(ConnectionState1[])(System.Array)new ConnectionState2[3];
Console.ReadKey();
}
}
06.枚举和字符串之间的转换
public enum State
{
One=100,
Two=200,
Three=300,
}
class Program
{
static void Main(string[] args)
{
//01 GetName :在指定枚举中检索具有指定值的常数的名称
string name =Enum.GetName(typeof(State), 100);
Console.WriteLine(name); // One
//02字符串转化为枚举
string s = "300";
object state=Enum.Parse(typeof(State), s);
Console.WriteLine(state); //Three
//03字符串转化为枚举
object state1;
bool success=Enum.TryParse(typeof(State), "200", out state1);
if (success)
{
Console.WriteLine(state1); //Two
}
//04字符串转化为枚举
State state2;
bool success1 = Enum.TryParse<State>("200", out state2);
if (success1)
{
Console.WriteLine(state2);//Two
}
Console.ReadKey();
}
}