在本文,你將學會如何遍歷并獲取枚舉的每一項,是一個非常實用的編程思想。文章末尾還備注有其他關于枚舉的小技巧哦
使用場景
筆者在學習Kinect過程中,發現其手勢枚舉多達27個(不包括用戶自定義的),而在某個項目中,如果這些手勢全部都用上,如果無腦操作,難免不會出現下面形式的代碼:
kmgr.DeleteGesture(userId, KinectGestures.Gestures.ShoulderLeftFront);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.ShoulderRightFront)
kmgr.DeleteGesture(userId, KinectGestures.Gestures.Psi);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.RaiseLeftHand);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.RaiseRightHand);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.Run);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.Stop);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.SwipeDown);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.SwipeLeft);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.SwipeRight);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.SwipeUp);
kmgr.DeleteGesture(userId, KinectGestures.Gestures.Tpose);
顯然,這個枚舉就是一個共通點,如果使用foreach遍歷枚舉并賦值,能將上述代碼簡化成如下樣子:
foreach (KinectGestures.Gestures item in Enum.GetValues(typeof(KinectGestures.Gestures)))
{
kmgr.DeleteGesture(userId, item);
}
示例學習:
using System;
using UnityEngine;
public enum TestEnumArr {
Test_01, Test_02, Test_03, Test_04, Test_05, Test_06,
Test_07, Test_08, Test_09, Test_10, Test_11, Test_12
};
public class TestForEnum : MonoBehaviour {
void Start () {
foreach (TestEnumArr item in Enum.GetValues(typeof(TestEnumArr)))
{
DoSomeThings(item);//這個方法證明我傳過去了枚舉
}
}
void DoSomeThings (TestEnumArr tEnum) {
Debug.Log(tEnum.ToString());//簡單演示枚舉項被轉過來了
switch (tEnum) //實際使用的一種情況,僅供參考
{
case TestEnumArr.Test_01:
Debug.Log("我是枚舉第一項"); //演示一下,下面的不寫了哈~
break;
}
}
}
動畫演示:
簡單演示
Tips:
1、枚舉+移位運算符的天配,味道會更好喲!
2、隨機獲得枚舉某一項思路,得到Value數組,隨機下標即可
3、判斷枚舉里面是否存在某一項
string msg="NotFound";
//int msg=100;
//HttpStatusCode msg=HttpStatusCode.Created;
Enum.IsDefined(typeof(HttpStatusCode),msg) //msg 可以是string ,也可以是數值,也可以是枚舉
(int)Enum.Parse(typeof(HttpStatusCode), msg)//將string類型的msg轉成枚舉,然后轉int類型的常數值
4、枚舉也要玩出鍵值對的感覺(KeyValuePair)
public enum PlantState
{
None=0,
Seed =1,
Child = 24 * 3 * 2,
Midd = Child + (int)(0.5f * 7 * 2), //如乘了float類型,必須這樣用上兩個括號
Old = Midd + (int)(0.5f * 50 * 2)
}
int total=0;
foreach (PlantState item in Enum.GetValues(typeof(PlantState)))
{
Debug.Log(item.ToString() + (int)item); //輸出:Seed1、Child144... 玩出鍵值對的感覺有木有!
total += (int)item;
}
- 怎么獲取枚舉類型的名稱呢?
_type.GetType().Name
想一想:結合筆者的TimeTrigger的OnUpdate回調返回的percentage如何玩出花來,再配合有限狀態機?
標簽:C#、Unity3D、Kinect、Enum枚舉、遍歷枚舉、