Get int value from enum in C#(从 C# 中的枚举中获取 int 值)
问题描述
我有一个名为Questions(复数)的课程.在这个类中有一个名为 Question(单数)的枚举,看起来像这样.
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
}
在 Questions 类中,我有一个 get(int foo) 函数,该函数为该 foo返回一个 Questions 对象代码>.有没有一种简单的方法可以从枚举中获取整数值,以便我可以执行类似 Questions.Get(Question.Role) 的操作?
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)?
推荐答案
只投枚举,例如
int something = (int) Question.Role;
上述方法适用于您在野外看到的绝大多数枚举,因为枚举的默认基础类型是 int.
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.
然而,正如 cecilphillip 指出的那样,枚举可以有不同的底层类型.如果枚举被声明为 uint、long 或 ulong,则应将其强制转换为枚举的类型;例如对于
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; e.g. for
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
你应该使用
long something = (long)StarsInMilkyWay.Wolf424B;
这篇关于从 C# 中的枚举中获取 int 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C# 中的枚举中获取 int 值
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
