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

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

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


当前回答

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

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

其他回答

我最喜欢的int或更小enums黑客:

GetHashCode();

对于枚举

public enum Test
{
    Min = Int32.MinValue,
    One = 1,
    Max = Int32.MaxValue,
}

var values = Enum.GetValues(typeof(Test));

foreach (var val in values)
{
    Console.WriteLine(val.GetHashCode());
    Console.WriteLine(((int)val));
    Console.WriteLine(val);
}

输出

one
1
1
max
2147483647
2147483647
min
-2147483648
-2147483648

免责声明:

它不适用于基于long的枚举。

在一个相关的注释中,如果你想从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。只需要提醒一下:

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

Use:

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

这将导致值==2。

只有当枚举适合于int时,这才是真的。

如果您想为存储在变量中的枚举值获取一个整数(其类型为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。