如何获得枚举在其定义列表中的数字位置? [英] How to get numeric position of an enum in its definition list?

查看:98
本文介绍了如何获得枚举在其定义列表中的数字位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取枚举在其定义中的数字位置。
考虑以下枚举-它用于位字段,但是状态名称
如果它们具有我已评论的右边的值,将很有用。

I need to get the numeric position of an enum in its definition. Consider the following enum - it is used for bit fields but the status names would be useful if they had the values on the right that I have commented.

[Flags]
public enum StatusFlags
{
    None = 0,                 // 0  -- these commented indexes are the numbers I also would like
    Untested = 1,             // 1     to associate with the enum names.
    Passed_Programming = 2,   // 2
    Failed_Programming = 4,   // 3
    // ... many more
}

我创建了一个如下所示的静态方法,该方法可以满足我的需要。

I have created a static method as follows, which works for what I want.

public static int GetStatusID(this StatusFlags flag)
{
   int i = 0;
   foreach (StatusFlags val in Enum.GetValues(typeof(StatusFlags)))
   {
      if (flag == val) break;
      i++;
   }
   return i;
}

它的用法如下:

StatusFlags f = StatusFlags.Failed_Programming;

// I want the position i.e value of 3 not the value the enum is associated with i.e 4
int Index = f.GetStatusID();

是否有更好的方法?

推荐答案

此处删除的答案表明类似以下内容

A deleted answer here suggested something that resembled

public static int GetStatusID(this StatusFlags flag)
{
    return Array.IndexOf(Enum.GetValues(typeof(StatusFlags)), flag);
}

只是缺少语法上的观点,即IndexOf是数组中的静态函数类,而不是扩展方法。出于简洁,我还是喜欢它。

and was just missing the syntactical point that IndexOf is a static function in the Array class, not an extension method. I like it though for brevity.

这篇关于如何获得枚举在其定义列表中的数字位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆