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

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

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


当前回答

例子:

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 question = Question.Role;
int value = (int) question;

将导致值==2。

int number = Question.Role.GetHashCode();

number的值应为2。

在Visual Basic中,它应该是:

Public Enum Question
    Role = 2
    ProjectFunding = 3
    TotalEmployee = 4
    NumberOfServers = 5
    TopBusinessConcern = 6
End Enum

Private value As Integer = CInt(Question.Role)

请改用扩展方法:

public static class ExtensionMethods
{
    public static int IntValue(this Enum argEnum)
    {
        return Convert.ToInt32(argEnum);
    }
}

用法更漂亮:

var intValue = Question.Role.IntValue();
public enum QuestionType
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

…是一个很好的声明。

您必须将结果强制转换为int,如下所示:

int Question = (int)QuestionType.Role

否则,类型仍然是QuestionType。

这种严格程度是C#的方式。

一种替代方法是改用类声明:

public class QuestionType
{
    public static int Role = 2,
    public static int ProjectFunding = 3,
    public static int TotalEmployee = 4,
    public static int NumberOfServers = 5,
    public static int TopBusinessConcern = 6
}

声明不那么优雅,但不需要将其转换为代码:

int Question = QuestionType.Role

或者,您可能会对Visual Basic感到更舒服,它在许多方面都满足了这种期望。