Enum枚举
定义枚举时可以指定基类型:
上面的ToString()方法隐式调用了Enum.Format()方法
Admin
GM
User
0 - Admin
1 - GM
2 - User
public enum AccountType : int
{
Admin = 0,
GM = 1,
User = 2
}
{
Admin = 0,
GM = 1,
User = 2
}
AccountType t = AccountType.Admin;
Console.WriteLine(t.ToString()); //输出"Admin"
Console.WriteLine(t.ToString("G")); //输出"Admin"
Console.WriteLine(t.ToString("D")); //输出"0"
Console.WriteLine(t.ToString()); //输出"Admin"
Console.WriteLine(t.ToString("G")); //输出"Admin"
Console.WriteLine(t.ToString("D")); //输出"0"
上面的ToString()方法隐式调用了Enum.Format()方法
Console.WriteLine(Enum.GetName(typeof(AccountType), 0)); //输出"Admin"
string[] names = Enum.GetNames(typeof(AccountType));
for (int i=0;i<names.Length;i++)
{
Console.WriteLine(string.Format("{0}", names[i]));
}
输出:for (int i=0;i<names.Length;i++)
{
Console.WriteLine(string.Format("{0}", names[i]));
}
Admin
GM
User
Array ary = Enum.GetValues(typeof(AccountType));
foreach(AccountType t in ary)
{
Console.WriteLine(t.ToString("D") + " - " + t.ToString("G"));
}
输出:foreach(AccountType t in ary)
{
Console.WriteLine(t.ToString("D") + " - " + t.ToString("G"));
}
0 - Admin
1 - GM
2 - User
Console.WriteLine(Enum.IsDefined(typeof(AccountType), 0).ToString()); //输出"True"
Console.WriteLine(Enum.IsDefined(typeof(AccountType), "Admin").ToString()); //输出"True" *注:区分大小写
Console.WriteLine(Enum.IsDefined(typeof(AccountType), "Admin").ToString()); //输出"True" *注:区分大小写