加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在其定义列表中获取枚举的数字位置

发布时间:2020-12-16 02:00:46 所属栏目:百科 来源:网络整理
导读:我需要在其定义中获取枚举的数字位置. 请考虑以下枚举 – 它用于位字段,但用于状态名称 如果他们有我评论的右边的值,那将会很有用. [Flags]public enum StatusFlags{ None = 0,// 0 -- these commented indexes are the numbers I also would like Untested
我需要在其定义中获取枚举的数字位置.
请考虑以下枚举 – 它用于位字段,但用于状态名称
如果他们有我评论的右边的值,那将会很有用.

[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
}

我创建了一个静态方法,如下所示,它适合我想要的.

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();

有没有更好的方法来做到这一点?

解决方法

这里删除的答案提示了类似的东西

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

并且只是缺少语法点,即IndexOf是Array类中的静态函数,而不是扩展方法.我喜欢它,但为了简洁起见.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读