Get int value from enum in C#

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

    Just cast the enum, e.g.

    int something = (int) Question.Role;
    

    The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

    However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

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

    you should use

    long something = (long)StarsInMilkyWay.Wolf424B;
    
    0 讨论(0)
  • 2020-11-22 05:27

    Following is the extension method

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 05:27

    My favourite hack with int or smaller enums:

    GetHashCode();
    

    For an enum

    public enum Test
    {
        Min = Int32.MinValue,
        One = 1,
        Max = Int32.MaxValue,
    }
    

    This,

    var values = Enum.GetValues(typeof(Test));
    
    foreach (var val in values)
    {
        Console.WriteLine(val.GetHashCode());
        Console.WriteLine(((int)val));
        Console.WriteLine(val);
    }
    

    outputs

    one
    1
    1
    max
    2147483647
    2147483647
    min
    -2147483648
    -2147483648
    

    Disclaimer:

    It doesn't work for enums based on long.

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

    I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).

    In light of that, below's how I'd now approach this issue (including implicit conversion to/from 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) =>
            question.index; //nb: if question is null this will return a null pointer exception
    
        public static implicit operator Question(int index) =>        
            values.TryGetValue(index, out var question) ? question : null;
    
        // Easy string conversion (also update ToString for the same effect)
        public override string ToString() =>
            this.name;
    
        public static implicit operator string(Question question) =>
            question?.ToString();
    
        public static implicit operator Question(string name) =>
            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) =>
            foo; //(implicit conversion will take care of the conversion for you)
    }
    

    The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of Question, you can put logic into Question itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.


    NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.

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

    You can do this by implementing an extension method to your defined enum type:

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

    This simplifies getting the int value of the current enum value:

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

    or

    int value = Question.Role.getNumberValue();
    
    0 讨论(0)
  • 2020-11-22 05:30

    Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

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

    This should work regardless of the underlying integral type.

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