8yue17
枚舉?
賦值給變量的有命名的整數(shù)常量的方法
定義:枚舉類型為定義了一組可以賦值給變量的命名整數(shù)常
量提供了一種有效方法,是一個整形常量集合,枚舉是一種值類型。
枚舉經(jīng)常應(yīng)用于對取值有限定的地方,比如星期只能是周一
到周日,月份只能是一月到十二月
枚舉聲明 enum
1、基礎(chǔ)類型默認(rèn)為int
//格式:enum 枚舉名{枚舉數(shù)0,枚舉數(shù)1...}
//例子:enum Season {Spring ,Summeer , Autumn , Winter}
//枚舉默認(rèn)的基礎(chǔ)類型是 Int,可以指定除char以為其他整形
//一般不設(shè)置情況下第一個為0? 后面依次累加
2、使用初始值來代替默認(rèn)值
enum Season {Spring = 1 ,Summeer , Autumn , Winter}
//3、指定枚舉基礎(chǔ)類型
enum Season:uint{ Spring,Summer,Autumn,Winter}
基礎(chǔ)類型可以是除char外的任何整型,包括byte,sbyte,short
ushort,int,uint,long或ulong
創(chuàng)建枚舉
格式:枚舉名 枚舉變量 = 枚舉名.枚舉值
Season first = Season.Spring;
Console.WriteLine (first);
//枚舉可以自增遞減
// wk++;//超出范圍后加的是 數(shù)字
Week wk = Week.Friday;
Test (Week.Thursday);
Console.WriteLine ("{0}",(int)wk);
枚舉數(shù)與關(guān)聯(lián)值的相互轉(zhuǎn)換
獲取枚舉數(shù)關(guān)聯(lián)的值需要對枚舉值進(jìn)行強(qiáng)制類型轉(zhuǎn)換:
int intValue = (int)Season.Spring;
打印intValue結(jié)果為0。
獲得某個值所對應(yīng)的枚舉數(shù)同樣要進(jìn)行強(qiáng)制類型轉(zhuǎn)換:
Season autumn = (Season)2;
打印autumn結(jié)果為Autumn。
注:當(dāng)不存在該枚舉數(shù)的時候則返回原數(shù)值。
獲取某一整數(shù)值關(guān)聯(lián)的枚舉數(shù)的名稱
一、
string str = Enum.GetName (typeof(Week) ,6);
string str_1 = ((Week)7).ToString ();
Console.WriteLine (str + ", " + str_1);
二、
int weapon = int.Parse (Console.ReadLine());
Console.WriteLine ("主角更換武器為:" + ((Weapon)weapon).ToString());
typeof方法 獲得當(dāng)前的類型
輸入枚舉值 得到對應(yīng)的Int值
Department dep = (Department)Enum.Parse( typeof (Department),"Market");
Console.WriteLine ("{0}",(int)dep);
?把整個枚舉轉(zhuǎn)化為string 的數(shù)組 通過數(shù)組下標(biāo)得到枚舉值
string [] atrArr = Enum.GetNames (typeof(Department));
Console.WriteLine (atrArr[0]);//3
Array numbers = Enum.GetValues (typeof(Department));
int n = (int)numbers.GetValue (0);
string str = Console.ReadLine ();
int? dep;
switch (str) {
case "Accounting":{
dep = (int)Department.Accounting;
break;
}
case "Administration":{
dep = (int)Department.Administration;
break;
}
default:{
Console.WriteLine ("錯誤");
break;
}
}
}
public static void Test (Week wk) {
switch (wk ){
case Week.Friday:
case Week.Monday:
case Week.Thursday:
case Week.Tuesday:
case Week.Wednesday:
{
Console.WriteLine ("今天是工作日");
break;
}
case Week.Saturday:
case Week.Sunday:
{
Console.WriteLine ("今天是周末");
break;
}
二分查找
//必須是有序數(shù)組
//k 是要找的數(shù) m是一半的數(shù)的下標(biāo)
//i 是第一個 j 是最后一個
// int []a={2,5,10,15,55,99,111,555};
// int low = 0, high = a.Length - 1;//低高位下標(biāo)
// int k = int.Parse(Console.ReadLine());//要找的數(shù)
// while (low <= high) {
// //求出中間下標(biāo)
// int mid = (low + high) / 2;
// if (a[mid] == k) {
// Console.WriteLine ("find,index = {0}",mid);
// return ;//結(jié)束整個方法
// //break;
// } else if (a[mid] < k) {
// low = mid + 1;
// } else {
// high= mid - 1;
// }
//
// }
// if(low > high){
// Console.WriteLine("404");//404網(wǎng)頁沒找到
// }