[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