Get int value from enum in C#

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

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

    ...is a fine declaration.

    You do have to cast the result to int like so:

    int Question = (int)QuestionType.Role
    

    Otherwise, the type is still QuestionType.

    This level of strictness is the C# way.

    One alternative is to use a class declaration instead:

    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
    }
    

    It's less elegant to declare, but you don't need to cast it in code:

    int Question = QuestionType.Role
    

    Alternatively, you may feel more comfortable with Visual Basic, which caters for this type of expectation in many areas.

提交回复
热议问题