How to get the int for enum value in Enumeration

This question already has an answer here:

  • Get int value from enum in C# 24 answers

  • To answer your question "how can I get the integer for string value":

    To convert from a string into an enum, and then convert the resulting enum to an int, you can do this:

    public enum Animals
    {
        dog = 0,
        cat = 1,
        rat = 2
    }
    
    ...
    
    Animals answer;
    
    if (Enum.TryParse("CAT", true, out answer))
    {
        int value = (int) answer;
        Console.WriteLine(value);
    }
    

    By the way, normal enum naming convention dictates that you should not pluralize your enum name unless it represents flag values (powers of two) where multiple bits can be set - so you should call it Animal , not Animals .


    Just cast your enum value to integer:

    Animals animal = Animals.dog;
    int value = (int)animal; // 0
    

    EDIT: if it turns out that you have name of enum value, then parse enum value and cast it to integer:

    int value = (int)Enum.Parse(typeof(Animals), "dog"); 
    

    您可以将其转换为Int或使用Enum.GetValues方法遍历所有值,该方法将检索指定枚举中常量值的数组。

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

    上一篇: 使用int最佳实践

    下一篇: 如何在Enumeration中获取int枚举值