Get int value from enum in C#

前端 未结 28 2562
臣服心动
臣服心动 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:21

    You should have used Type Casting as we can use in any other language.

    If your enum is like this-

    public enum Question
    {
        Role = 2,
        ProjectFunding = 3,
        TotalEmployee = 4,
        NumberOfServers = 5,
        TopBusinessConcern = 6
    }
    

    And you need to cast to an int, then do this-

    Question q = Question.Role;
    .............
    .............
    int something = (int) q;
    

    Re-

    In C#, there are two types of casting:

    • Implicit Casting (automatically) - converting a smaller type to a larger type size like-

    char -> int -> long -> float -> double

    • Explicit Casting (manually) - converting a larger type to a smaller size type like-

    double -> float -> long -> int -> char

    More can be found in here.

提交回复
热议问题