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

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

在Questions类中,我有一个get(intfoo)函数,它为该foo返回Questions对象。有没有一种简单的方法可以从枚举中获取整数值,这样我就可以执行类似于Questions.get(Questions.Role)的操作?


当前回答

将为您提供一个列表,其中包含枚举的所有整数值:

List enumValues=Enum.GetValues(typeof(EnumClass)).Cast().ToList();

其他回答

您可以通过对定义的枚举类型实现一个扩展方法来做到这一点:

public static class MyExtensions
{
    public static int getNumberValue(this Question questionThis)
    {
        return (int)questionThis;
    }
}

这简化了获取当前枚举值的int值:

Question question = Question.Role;
int value = question.getNumberValue();

or

int value = Question.Role.getNumberValue();

例子:

public enum EmpNo
{
    Raj = 1,
    Rahul,
    Priyanka
}

在后面的代码中获取枚举值:

int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1

or

int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2

枚举将递增1,您可以设置起始值。如果不设置起始值,初始值将指定为0。

如果您想为存储在变量中的枚举值获取一个整数(其类型为Question),以便在方法中使用,您可以简单地执行我在本例中编写的操作:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

这会将窗口标题更改为4,因为变量Geselecterd是Talen.Nedelands。如果我将其更改为Talen.Portuges并再次调用该方法,文本将更改为3。

尝试使用此方法,而不是将enum转换为int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}

将其声明为具有公共常量的静态类:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

然后,您可以将其引用为Question.Role,它的计算结果始终为int或您定义的任何值。