2009-09-15 79 views
2
[FlagsAttribute] 
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }; 

我有一个枚举显示。我想能够得到说Colors.Blue是在索引2,索引从0.我想要获得在索引中传递的颜色。什么?有人可以张贴我一些片断......按值枚举索引

回答

3

假设每种颜色使用单个位的值,你可以找到该位的索引。

public int GetIndex(Colors color) { 
    int value = (int)colors; 
    int index = 0; 
    while (value > 0) { 
     value >>= 1; 
     index++; 
    } 
    return index; 
} 

请注意,位的索引通常是基于零的,但在这里您会得到一个基于索引的索引。

如果你想要一个基于零的索引,你会得到蓝色的索引2,而不是你在问题中提到的那样。如果那是您想要的结果,请从index = -1;开始。

+0

抱歉索引,我现在将其更改为2 – chugh97 2009-09-15 11:21:37

2

不能真正理解你的问题,但是这是你的意思:

var blue = (Colors)Enum.GetValues(typeof(Colors))[2]; 
+1

您将得到无法与应用索引[ ]转换为'System.Array'类型的表达式;) – 2009-09-15 11:11:23

11

试试这个:

int index = Array.IndexOf(Enum.GetValues(typeof(Colors)), Colors.Green); 
1

我不知道为什么你需要它,但这样做的一个方法是

Colors c = (Colors)Enum.Parse(typeof(Colors), Enum.GetNames(typeof(Colors))[index]); 
0

这是我发现的最简单的解决方案。可以很好地处理标志,而不用打扰字节操作。

Array eVals = Enum.GetValues(typeof(MyEnum)); 
MyEnum eVal = (MyEnum)eVals.GetValue(iIndex); 
0

我做这样以后这方面的工作:

return (Status)Enum.GetValues(typeof(Status)).GetValue(this.EvaluationStatusId); 
0

我用下面的代码,它工作:

int index=(int)Enum.Parse(typeof(Colors), "Green");