Get int value from enum in C#

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

    I came up with this extension method that includes current language features. By using dynamic, I don't need to make this a generic method and specify the type which keeps the invocation simpler and consistent:

    public static class EnumEx
    {
        public static dynamic Value(this Enum e)
        {
            switch (e.GetTypeCode())
            {
                case TypeCode.Byte:
                {
                    return (byte) (IConvertible) e;
                }
    
                case TypeCode.Int16:
                {
                    return (short) (IConvertible) e;
                }
    
                case TypeCode.Int32:
                {
                    return (int) (IConvertible) e;
                }
    
                case TypeCode.Int64:
                {
                    return (long) (IConvertible) e;
                }
    
                case TypeCode.UInt16:
                {
                    return (ushort) (IConvertible) e;
                }
    
                case TypeCode.UInt32:
                {
                    return (uint) (IConvertible) e;
                }
    
                case TypeCode.UInt64:
                {
                    return (ulong) (IConvertible) e;
                }
    
                case TypeCode.SByte:
                {
                    return (sbyte) (IConvertible) e;
                }
            }
    
            return 0;
        }
    

提交回复
热议问题