Get int value from enum in C#

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

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

In the Questions class, I have a get(int foo) function that returns a Questions object for that foo . Is there an easy way to get the integer value from the enum so I can do something like Questions.Get(Question.Role) ?


Just cast the enum, eg

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int .

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint , long , or ulong , it should be cast to the type of the enum; eg for

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

you should use

long something = (long)StarsInMilkyWay.Wolf424B;

Since Enums can be any integral type ( byte , int , short , etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

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

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

This should work regardless of the underlying integral type.


Declare it as a static class having public constants:

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;
}

And then you can reference it as Question.Role , and it always evaluates to an int or whatever you define it as.

链接地址: http://www.djcxy.com/p/2670.html

上一篇: 'for'循环遍历Java中的枚举

下一篇: 从C#中的枚举中获取int值