[FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
我有一個枚舉顯示。我想能夠得到說Colors.Blue是在索引2,索引從0.我想要獲得在索引中傳遞的顏色。什麼?有人可以張貼我一些片斷......按值枚舉索引
[FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
我有一個枚舉顯示。我想能夠得到說Colors.Blue是在索引2,索引從0.我想要獲得在索引中傳遞的顏色。什麼?有人可以張貼我一些片斷......按值枚舉索引
假設每種顏色使用單個位的值,你可以找到該位的索引。
public int GetIndex(Colors color) {
int value = (int)colors;
int index = 0;
while (value > 0) {
value >>= 1;
index++;
}
return index;
}
請注意,位的索引通常是基於零的,但在這裏您會得到一個基於索引的索引。
如果你想要一個基於零的索引,你會得到藍色的索引2,而不是你在問題中提到的那樣。如果那是您想要的結果,請從index = -1;
開始。
不能真正理解你的問題,但是這是你的意思:
var blue = (Colors)Enum.GetValues(typeof(Colors))[2];
您將得到無法與應用索引[ ]轉換爲'System.Array'類型的表達式;) – 2009-09-15 11:11:23
試試這個:
int index = Array.IndexOf(Enum.GetValues(typeof(Colors)), Colors.Green);
我不知道爲什麼你需要它,但這樣做的一個方法是
Colors c = (Colors)Enum.Parse(typeof(Colors), Enum.GetNames(typeof(Colors))[index]);
這是我發現的最簡單的解決方案。可以很好地處理標誌,而不用打擾字節操作。
Array eVals = Enum.GetValues(typeof(MyEnum));
MyEnum eVal = (MyEnum)eVals.GetValue(iIndex);
我做這樣以後這方面的工作:
return (Status)Enum.GetValues(typeof(Status)).GetValue(this.EvaluationStatusId);
我用下面的代碼,它工作:
int index=(int)Enum.Parse(typeof(Colors), "Green");
抱歉索引,我現在將其更改爲2 – chugh97 2009-09-15 11:21:37