在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)

只是抛出枚举例如。

 int something = (int)Question.Role; 

以上将适用于绝大多数在野外看到的枚举,因为枚举的默认基础类型是int。

但是正如cecilphillip所指出的,枚举可以有不同的基础类型。 如果枚举被声明为uint,long或ulong,那么它应该被转换为枚举的类型。

例如

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

你应该使用

 long something = (long)StarsInMilkyWay.Wolf424B; 

由于枚举可以是任何整型(short,byte,int等),所以获得枚举底层整型值的更健壮的方法是使用GetTypeCode方法和Convert类

 enum Sides { Left, Right, Top, Bottom } Sides side = Sides.Bottom; object val = Convert.ChangeType(side, side.GetTypeCode()); Console.WriteLine(val); 

这应该工作,不管底层整型的类型。

将它声明为一个静态类,其中包含常量。

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

然后你可以引用它作为Question.Role它总是评估一个int或任何你定义它。

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

将导致value == 2

在相关说明中,如果您想从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 

编辑 :每个枚举类型都有一个基础类型,可以是除char之外的任何整数类型。

例:

 Public Enum EmpNo { Raj = 1 Rahul, Priyanka } 

并在后面的代码获取枚举值:

 int setempNo = (int)EmpNo.Raj; //This will give setempNo = 1 

要么

 int setempNo = (int)EmpNo.Rahul; //This will give setempNo = 2 

枚举将以1递增,您可以设置起始值。 否则它将被初始化为0。

我最近转换了在我的代码中使用枚举,赞成使用具有受保护的构造函数和预定义的静态实例的类(感谢Roelof – C#确保有效的枚举值 – 未来防御方法 )。

鉴于此,下面是我现在要解决这个问题的方法(包括向/从int的隐式转换)。

 public class Question { //attributes protected int index; protected string name; //go with a dictionary to enforce unique index //protected static readonly ICollection<Question> values = new Collection<Question>(); protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>(); //define the "enum" values public static readonly Question Role = new Question(2,"Role"); public static readonly Question ProjectFunding = new Question(3, "Project Funding"); public static readonly Question TotalEmployee = new Question(4, "Total Employee"); public static readonly Question NumberOfServers = new Question(5, "Number of Servers"); public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern"); //constructors protected Question(int index, string name) { this.index = index; this.name = name; values.Add(index, this); } //easy int conversion public static implicit operator int(Question question) { return question.index; //nb: if question is null this will return a null pointer exception } public static implicit operator Question(int index) { //return values.FirstOrDefault(item => index.Equals(item.index)); Question question; values.TryGetValue(index, out question); return question; } //easy string conversion (also update ToString for the same effect) public override string ToString() { return this.name; } public static implicit operator string(Question question) { return question == null ? null : question.ToString(); } public static implicit operator Question(string name) { return name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase)); } //if you specifically want a Get(int x) function (though not required given the implicit converstion) public Question Get(int foo) { return foo; //(implicit conversion will take care of the conversion for you) } } 

这种方法的好处是你可以从枚举中得到所有的东西,但是你的代码现在更加灵活了,所以如果你需要根据问题的价值来执行不同的操作,你可以把逻辑放到问题本身(即在首选OO时尚),而不是在整个代码中放置大量的case语句来处理每个场景。

如果你想获得一个整型的枚举值存储在一个变量,至于类型将是“问题”,例如在一个方法中使用,你可以简单地做到这一点,我写在这个例子中:

 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 parameter, so any enumaration from any enumerator can be used as parameter void VeranderenTitel(Enum e) { this.Text = Convert.ToInt32(e).ToString(); } 

这将改变窗口标题为4,因为变量“Geselecteerd”是“Talen.Nederlands”。 如果我将其更改为“Talen.Portugees”并再次调用该方法,文本将更改为3。

我很难在网络上找到这个简单的解决方案,而且我找不到它,所以我正在测试somtehings,并发现了这一点。 希望这可以帮助。 ;)

为了确保枚举值存在,然后解析它,还可以执行以下操作。

 // 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() + "."); 

我希望这有帮助。

还有一种方法可以做到这一点:

 Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role); 

将导致:

 Name: Role, Value: 2 

也许我错过了,但有人试过一个简单的通用扩展方法。 这对我很好。 您可以通过这种方式避免在API中进行类型转换,但最终会导致更改类型的操作。 这是编程Roselyn使编译器为您创建GetValue方法的好例子。

  public static void Main() { int test = MyCSharpWrapperMethod(TestEnum.Test1); Debug.Assert(test == 1); } public static int MyCSharpWrapperMethod(TestEnum customFlag) { return MyCPlusPlusMethod(customFlag.GetValue<int>()); } public static int MyCPlusPlusMethod(int customFlag) { //Pretend you made a PInvoke or COM+ call to C++ method that require an integer return customFlag; } public enum TestEnum { Test1 = 1, Test2 = 2, Test3 = 3 } } public static class EnumExtensions { public static T GetValue<T>(this Enum enumeration) { T result = default(T); try { result = (T)Convert.ChangeType(enumeration, typeof(T)); } catch (Exception ex) { Debug.Assert(false); Debug.WriteLine(ex); } return result; } } 

您可以通过将扩展方法实现为您定义的枚举类型来完成此操作:

 public static class MyExtensions { public static int getNumberValue(this Question questionThis) { return (int)questionThis; } } 

这简化了获取当前枚举值的int值:

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

要么

 int value = Question.Role.getNumberValue(); 
 public enum QuestionType { Role = 2, ProjectFunding = 3, TotalEmployee = 4, NumberOfServers = 5, TopBusinessConcern = 6 } 

…是一个很好的声明。

您必须将结果转换为int,如下所示:

 int Question = (int)QuestionType.Role 

如果你不那么它的类型仍然是QuestionType。

恐怕这是C#的方式有这个严格的水平。

另一种方法是使用类声明来代替:

 public class QuestionType { public static int Role = 2, public static int ProjectFunding = 3, public static int TotalEmployee = 4, public static int NumberOfServers = 5, public static int TopBusinessConcern = 6 } 

声明不那么优雅,但你不需要在代码中强制转换:

 int Question = QuestionType.Role 

或者,您可能会对Visual Basic感到更加舒适,Visual Basic在许多领域都能满足这种期望。

 int number = Question.Role.GetHashCode(); 

number应该是2的值。

如何扩展方法,而不是:

 public static class ExtensionMethods { public static int IntValue(this Enum argEnum) { return Convert.ToInt32(argEnum); } } 

用法稍微漂亮些:

 var intValue = Question.Role.IntValue(); 

以下是扩展方法

 public static string ToEnumString<TEnum>(this int enumValue) { var enumString = enumValue.ToString(); if (Enum.IsDefined(typeof(TEnum), enumValue)) { enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString(); } return enumString; } 

我能想到的最简单的解决方法是像这样重载Get(int)方法:

 [modifiers] Questions Get(Question q) { return Get((int)q); } 

其中[modifiers]一般可以和Get(int)方法相同。 如果您不能编辑Questions类或出于某种原因不想要,可以通过编写扩展来重载该方法:

 public static class Extensions { public static Questions Get(this Questions qs, Question q) { return qs.Get((int)q); } } 

试试这个,而不是将enum转换为int:

 public static class ReturnType { public static readonly int Success = 1; public static readonly int Duplicate = 2; public static readonly int Error = -1; } 

我的收入破解int或更小的枚举:

 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的枚举不起作用

我想建议'从枚举中获得'int'值的例子是'

 public enum Sample {Book =1, Pen=2, Pencil =3} int answer = (int)Sample.Book; 

现在答案将是1。

我希望这可以帮助某人。

在Vb。 它应该是

 Public Enum Question Role = 2 ProjectFunding = 3 TotalEmployee = 4 NumberOfServers = 5 TopBusinessConcern = 6 End Enum Private value As Integer = CInt(Question.Role) 

尝试这个 :

 int value = YourEnum.ToString("D");