Enum枚举

定义枚举时可以指定基类型:
public enum AccountType : int
{
    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"

上面的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]));
}
输出:
Admin
GM
User

Array ary = Enum.GetValues(typeof(AccountType));
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"     *注:区分大小写





posted @ 2007-05-10 22:05  蛤蟆  阅读(478)  评论(1)    收藏  举报