从 C# 中的枚举中获取 int 值
我有一个名为 Questions
(复数)的课程。 在这个类中,有一个名为 Question
(单数)的枚举,如下所示。
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
在 Questions
类中,我有一个 get(int foo)
函数,它返回该 foo
的 Questions
对象。 有没有一种简单的方法可以从枚举中获取整数值,以便我可以执行类似 Questions.Get(Question.Role)
的操作?
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 off the enum so I can do something like this Questions.Get(Question.Role)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
只需转换枚举,例如
上面的内容适用于您在野外看到的绝大多数枚举,因为枚举的默认基础类型是
int
。但是,正如 cecilphillip 指出的那样,枚举可以具有不同的基础类型。
如果枚举被声明为
uint
、long
或ulong
,则应将其强制转换为枚举的类型; 例如你应该使用
Just cast the enum, e.g.
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
, orulong
, it should be cast to the type of the enum; e.g. foryou should use
由于枚举可以是任何整数类型(
byte
、int
、short
等),因此有一种更可靠的方法来获取底层整数值枚举将结合使用GetTypeCode
方法和Convert
类:无论底层整数类型如何,这都应该有效。
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 theGetTypeCode
method in conjunction with theConvert
class:This should work regardless of the underlying integral type.
将其声明为具有公共常量的静态类:
然后您可以将其引用为
Question.Role
,并且它的计算结果始终为int
或您将其定义为的任何内容。Declare it as a static class having public constants:
And then you can reference it as
Question.Role
, and it always evaluates to anint
or whatever you define it as.说明,如果您想从
System.Enum
获取int
值,则在此处给出e
:您可以使用:
相关 两个简直丑陋。 我更喜欢第一个。
On a related note, if you want to get the
int
value fromSystem.Enum
, then givene
here:You can use:
The last two are plain ugly. I prefer the first one.
将导致
value == 2
。Will result in
value == 2
.示例:
并在后面的代码中获取枚举值:
否则
Enums将增加1,并且可以设置起始值。 如果您不设置起始值,它将最初被指定为 0。
Example:
And in the code behind to get the enum value:
or
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.
这比你想象的要容易——枚举已经是整数了。 只是需要提醒的是:
It's easier than you think - an enum is already an int. It just needs to be reminded:
我最近不再在代码中使用枚举,而是使用带有受保护构造函数和预定义静态实例的类(感谢 Roelof - C# 确保有效的枚举值 - 面向未来的方法)。
鉴于此,下面是我现在解决此问题的方法(包括与
int
之间的隐式转换)。这种方法的优点是您可以从枚举中获得所有内容,但您的代码现在更加灵活,因此如果您需要根据
Question
的值执行不同的操作,您可以将逻辑放入Question
本身(即以首选的 OO 方式),而不是在代码中放置大量 case 语句来处理每个场景。注意:答案于 2018-04-27 更新,以利用 C# 6 功能; 即声明表达式和 lambda 表达式主体定义。 请参阅修订历史记录了解原始代码。 这样做的好处是使定义不那么冗长; 这是对此答案方法的主要抱怨之一。
I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).
In light of that, below's how I'd now approach this issue (including implicit conversion to/from
int
).The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of
Question
, you can put logic intoQuestion
itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.
如果您想获取存储在变量中的枚举值的整数(其类型为
Question
),以便在方法中使用,您可以简单地执行我在本文中编写的操作示例:这会将窗口标题更改为 4,因为变量
Geselecteerd
是Talen.Nederlands
。 如果我将其更改为Talen.Portugees
并再次调用该方法,文本将更改为 3。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:This will change the window title to 4, because the variable
Geselecteerd
isTalen.Nederlands
. If I change it toTalen.Portugees
and call the method again, the text will change to 3.使用扩展方法代替:
并且用法稍微漂亮一些:
Use an extension method instead:
And the usage is slightly prettier:
另一种方法:
它将导致:
One more way to do it:
It will result in:
要确保枚举值存在并解析它,您还可以执行以下操作。
To ensure an enum value exists and then parse it, you can also do the following.
使用:
它将产生
value == 2
。仅当枚举适合
int
时,这才是正确的。Use:
It will result in
value == 2
.This is only true if the enum fits inside an
int
.……这是一个很好的声明。
您必须像这样将结果转换为 int:
否则,类型仍然是
QuestionType
。这种严格程度是 C# 的方式。
一种替代方法是使用类声明:
声明不太优雅,但您不需要在代码中对其进行强制转换:
或者,您可能更喜欢使用 Visual Basic,它在许多领域满足了这种类型的期望。
...is a fine declaration.
You do have to cast the result to int like so:
Otherwise, the type is still
QuestionType
.This level of strictness is the C# way.
One alternative is to use a class declaration instead:
It's less elegant to declare, but you don't need to cast it in code:
Alternatively, you may feel more comfortable with Visual Basic, which caters for this type of expectation in many areas.
也许我错过了,但是有人尝试过简单的通用扩展方法吗?
这对我来说非常有用。 您可以通过这种方式避免 API 中的类型转换,但最终会导致更改类型操作。 这是一个很好的例子,可以对 Roslyn 进行编程,让编译器生成 GetValue。 方法给你。
Maybe I missed it, but has anyone tried a simple generic extension method?
This works great for me. You can avoid the type cast in your API this way but ultimately it results in a change type operation. This is a good case for programming Roslyn to have the compiler make a GetValue<T> method for you.
number
的值应为2
。number
should have the value2
.您可以通过对定义的枚举类型实施扩展方法来实现此目的:
这简化了获取 int当前枚举值的值:
或
You can do this by implementing an extension method to your defined enum type:
This simplifies getting the int value of the current enum value:
or
由于可以使用多个基元类型来声明枚举,因此用于转换任何枚举类型的通用扩展方法可能会很有用。
Since enums can be declared with multiple primitive types, a generic extension method to cast any enum type can be useful.
您应该使用类型转换 正如我们可以在任何其他语言中使用的那样。
如果您的
enum
是这样的 -并且您需要转换为
int
,然后执行此操作-
在 C# 中,有两种类型的转换:
更多信息请参见此处。
You should have used Type Casting as we can use in any other language.
If your
enum
is like this-And you need to cast to an
int
, then do this-Re-
In C#, there are two types of casting:
More can be found in here.
我能想到的最简单的解决方案是重载
Get(int)
方法,如下所示:其中
[modifiers]
通常可以与Get(int) 相同方法。 如果您无法编辑
Questions
类或由于某种原因不想编辑,您可以通过编写扩展来重载该方法:The easiest solution I can think of is overloading the
Get(int)
method like this:where
[modifiers]
can generally be same as for theGet(int)
method. If you can't edit theQuestions
class or for some reason don't want to, you can overload the method by writing an extension:我最喜欢的使用 int 或更小的枚举的技巧:
对于枚举
,
输出
免责声明:
它不适用于基于 long 的枚举。
My favourite hack with int or smaller enums:
For an enum
This,
outputs
Disclaimer:
It doesn't work for enums based on long.
我想建议的例子是“从枚举中获取‘int’值”,
现在答案是 1。
The example I would like to suggest "to get an 'int' value from an enum", is
Now the answer will be 1.
尝试这个而不是将 enum 转换为 int:
Try this one instead of convert enum to int:
下面是扩展方法
Following is the extension method
在 Visual Basic 中,它应该是:
In Visual Basic, it should be:
将为您提供一个包含枚举的所有整数值的列表:
List enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();
will give you the a list with all the integer values of the enum :
List enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();
几乎所有当前答案都在目标类型之前使用
Convert
或强制转换为对象,这会导致装箱和拆箱操作。 这会导致堆分配,并且对于热路径来说可能不可接受。由于大部分答案都是书面的,System.Runtime.CompilerServices.Unsafe,支持对指针的低级操作。
与泛型相结合,
Unsafe
类允许我们安全地更改System.Enum
参数的基础类型,零分配,并且性能与空方法持续时间:如果最好始终返回 int,则可以这样做,但如果枚举的支持字段超过
int.MaxValue
,则会溢出:如果使用以下内容:
-2147483648
将由于溢出而返回。 开发人员极不可能创建具有如此大标志值的枚举,但总是有可能的。Nearly all of the current answers use
Convert
or cast to object before the target type, which results in boxing and unboxing operations. This causes heap allocations and may not be acceptable for hot paths.Since the majority of these answers were written, System.Runtime.CompilerServices.Unsafe was introduced, enabling low-level manipulation of pointers.
In combination with generics, the
Unsafe
class allows us to change the underlying type of theSystem.Enum
parameter safely, with zero allocations, and with performance that is nearly indistinguishable from an empty method duration:If it is preferable to always return an int, you can do so, although if the backing field of the enum exceeds
int.MaxValue
, it will overflow:If the following were used:
-2147483648
would be returned due to an overflow. It is extremely unlikely that developers would create enums with such large flag values, but is always a possibility.我正在遵循这种方法来访问 Enums 的值
并使用此方法调用
,或者,您可以通过以下方式将枚举值返回为 int
I'm following this approach to access the value of Enums
and to use this method call
or, you can return the enum value as int by