按值列出的枚举索引
[FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
我有一个枚举如图所示。我希望能够获得说 Colors.Blue 位于索引 2,索引从 0 开始的能力。我想获得传入 Colors 的索引号。无论如何?有人可以给我发一些片段吗...
[FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
I have an enum as show. I want the ability to get say Colors.Blue is at index 2, index staring from 0.I want to get the index number passing in Colors.Whatever? Can someone post me some snippets...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
试试这个:
Try this one:
假设每种颜色使用单个位作为值,您只需找到该位的索引即可。
请注意,位索引通常是从零开始的,但这里您得到的是从一开始的索引。
如果您想要一个从零开始的索引,您将得到蓝色的索引二,而不是问题中所述的三。如果这是您想要的结果,请从
index = -1;
开始。Assuming that each color uses a single bit as value, you can just locate the index of that bit.
Note that the index of bits is normally zero based, but here you get a one based index.
If you want a zero based index, you would get the index two for blue, not three as you stated in the question. Just start with
index = -1;
if that is the result that you desire.不太明白你的问题,但你的意思是这样的:
Can't really understand your question, but is this what you mean:
我不知道你为什么需要它,但一种方法是
I don't know why you need it , but one way to do that is
这是我发现的最简单的解决方案。与标志一起工作正常,无需担心字节操作。
This is the easiest solution I found. Works fine with flags w/o bothering with bytes operations.
我这样做后得到了这个工作:
I got this working after doing it like this:
我正在使用以下代码,并且它正在工作:
I am using the following code, and it is working: