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

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

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


当前回答

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

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

其他回答

由于枚举可以是任何整数类型(byte、int、short等),因此获取枚举的基本整数值的更可靠的方法是将GetTypeCode方法与Convert类结合使用:

enum Sides {
    Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);

无论基础的整数类型如何,这都应该有效。

请改用扩展方法:

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

用法更漂亮:

var intValue = Question.Role.IntValue();

在一个相关的注释中,如果你想从System.Enum中获取int值,那么在这里给出e:

Enum e = Question.Role;

您可以使用:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

最后两个很难看。我更喜欢第一个。

int number = Question.Role.GetHashCode();

number的值应为2。

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

// 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() + ".");