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

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

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


当前回答

为了确保枚举值存在,然后解析它,还可以执行以下操作。

// Fake Day of Week
string strDOWFake = "SuperDay";

// Real Day of Week
string strDOWReal = "Friday";

// Will hold which ever is the real DOW.
DayOfWeek enmDOW;

// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
    // This will never be reached since "SuperDay"
    // doesn't exist in the DayOfWeek enumeration.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
    // This will parse the string into it's corresponding DOW enum object.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}

// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");

其他回答

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感到更舒服,它在许多方面都满足了这种期望。

在Visual Basic中,它应该是:

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

Private value As Integer = CInt(Question.Role)

这比你想象的要简单-枚举已经是int。只需要提醒一下:

int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2

只需转换枚举,例如。

int something = (int) Question.Role;

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

然而,正如cecilphilip所指出的,遗尿症可能有不同的潜在类型。如果枚举声明为uint、long或ulong,则应将其强制转换为枚举的类型;例如,用于

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

你应该使用

long something = (long)StarsInMilkyWay.Wolf424B;

由于枚举可以用多个基元类型声明,因此可以使用泛型扩展方法来转换任何枚举类型。

enum Box
{
    HEIGHT,
    WIDTH,
    DEPTH
}

public static void UseEnum()
{
    int height = Box.HEIGHT.GetEnumValue<int>();
    int width = Box.WIDTH.GetEnumValue<int>();
    int depth = Box.DEPTH.GetEnumValue<int>();
}

public static T GetEnumValue<T>(this object e) => (T)e;