从C#中的枚举中获取int值

从C#中的枚举中获取int值

问题描述:

我有一个名为的课程(复数)。在这个类中有一个名为 Question (单数)的枚举,看起来像这样。

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

问题 class,我有一个 get(int foo)函数,它为 Questions 对象> FOO 。有没有一种简单的方法可以从枚举中获取整数值,所以我可以做一些像 Questions.Get(Question.Role)

In the Questions class, I have a get(int foo) function that returns a Questions object for that foo. Is there an easy way to get the integer value from the enum so I can do something like Questions.Get(Question.Role)?

只需转换枚举,例如

int something = (int) Question.Role;

以上内容适用于您在野外看到的绝大多数枚举,作为默认的基础类型对于枚举是 int

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

但是,如 cecilphillip 指出,枚举可以有不同的底层类型。
如果枚举声明为 uint long ulong ,它应该转换为枚举的类型;例如for

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

你应该使用

long something = (long)StarsInMilkyWay.Wolf424B;