Get int value from enum in C#

前端 未结 28 1888
臣服心动
臣服心动 2020-11-22 04:58

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public e         


        
相关标签:
28条回答
  • 2020-11-22 05:42

    Since enums can be declared with multiple primitive types, a generic extension method to cast any enum type can be useful.

    enum Box
    {
        HEIGHT,
        WIDTH,
        DEPTH
    }
    
    public static void UseEnum()
    {
        int height = Box.HEIGHT.GetEnumValue<int>();
        int width = Box.WIDTH.GetEnumValue<int>();
        int depth = Box.DEPTH.GetEnumValue<int>();
    }
    
    public static T GetEnumValue<T>(this object e) => (T)e;
    
    0 讨论(0)
  • 2020-11-22 05:43

    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:

    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.

    0 讨论(0)
  • 2020-11-22 05:45

    On a related note, if you want to get the int value from System.Enum, then given e here:

    Enum e = Question.Role;
    

    You can use:

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

    The last two are plain ugly. I prefer the first one.

    0 讨论(0)
  • 2020-11-22 05:45

    The example I would like to suggest "to get an 'int' value from an enum", is

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

    Now the answer will be 1.

    0 讨论(0)
提交回复
热议问题