从 C# 中的枚举获取 int 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/943398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get int value from enum in C#
提问by jim
I have a class called Questions
(plural). In this class there is an enum called Question
(singular) which looks like this.
我有一个班级叫Questions
(复数)。在这个类中有一个名为Question
(singular)的枚举,它看起来像这样。
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 off the enum so I can do something like this Questions.Get(Question.Role)
?
在Questions
类中,我有一个get(int foo)
函数,它返回一个Questions
对象foo
。有没有一种简单的方法可以从枚举中获取整数值,以便我可以做这样的事情Questions.Get(Question.Role)
?
采纳答案by Tetraneutron
Just cast the enum, e.g.
只需投射枚举,例如
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
.
以上将适用于您在野外看到的绝大多数枚举,因为枚举的默认基础类型是int
.
However, as cecilphillippoints 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; e.g. for
然而,正如cecilphillip指出的那样,枚举可以有不同的基础类型。如果枚举被声明为 a uint
, long
, or ulong
,则应将其强制转换为枚举的类型;例如对于
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
你应该使用
long something = (long)StarsInMilkyWay.Wolf424B;
回答by jerryjvl
Question question = Question.Role;
int value = (int) question;
Will result in value == 2
.
将导致value == 2
.
回答by Michael Petrotta
It's easier than you think - an enum is already an int. It just needs to be reminded:
这比您想象的要容易 - 枚举已经是一个整数。只需要提醒一下:
int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2
回答by Michael Petrotta
Example:
例子:
public Enum EmpNo
{
Raj = 1,
Rahul,
Priyanka
}
And in the code behind to get the enum value:
并在后面的代码中获取枚举值:
int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1
or
或者
int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2
Enums will increment by 1, and you can set the start value. If you don't set the start value it will be assigned as 0 initially.
枚举将递增 1,您可以设置起始值。如果您不设置起始值,它最初将被分配为 0。
回答by cecilphillip
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 可以是任何整数类型(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);
This should work regardless of the underlying integral type.
无论底层的整数类型如何,这都应该有效。
回答by Nathon
To ensure an enum value exists and then parse it, you can also do the following.
为了确保枚举值存在然后解析它,您还可以执行以下操作。
// 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() + ".");
回答by Mathijs Van Der Slagt
If you want to get an integer for the enum value that is stored in a variable, for which the type would be Question
, to use for example in a method, you can simply do this I wrote in this example:
如果您想获取存储在变量中的枚举值的整数,其类型为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();
}
This will change the window title to 4, because the variable Geselecteerd
is Talen.Nederlands
. If I change it to Talen.Portugees
and call the method again, the text will change to 3.
这会将窗口标题更改为 4,因为变量Geselecteerd
是Talen.Nederlands
. 如果我将其更改为Talen.Portugees
并再次调用该方法,则文本将更改为 3。
回答by PablosBicicleta
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.
然后您可以将其引用为Question.Role
,并且它始终评估为 anint
或您定义的任何内容。
回答by Bronek
You can do this by implementing an extension methodto your defined enum type:
您可以通过对定义的枚举类型实现扩展方法来实现此目的:
public static class MyExtensions
{
public static int getNumberValue(this Question questionThis)
{
return (int)questionThis;
}
}
This simplifies getting the int value of the current enum value:
这简化了获取当前枚举值的 int 值:
Question question = Question.Role;
int value = question.getNumberValue();
or
或者
int value = Question.Role.getNumberValue();
回答by Grx70
The easiest solution I can think of is overloading the Get(int)
method like this:
我能想到的最简单的解决方案是Get(int)
像这样重载方法:
[modifiers] Questions Get(Question q)
{
return Get((int)q);
}
where [modifiers]
can generally be same as for the Get(int)
method. If you can't edit the Questions
class or for some reason don't want to, you can overload the method by writing an extension:
where[modifiers]
通常与Get(int)
方法相同。如果您无法编辑Questions
类或出于某种原因不想编辑,您可以通过编写扩展来重载该方法:
public static class Extensions
{
public static Questions Get(this Questions qs, Question q)
{
return qs.Get((int)q);
}
}