Get int value from enum in C#

前端 未结 28 1955
臣服心动
臣服心动 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条回答
  •  -上瘾入骨i
    2020-11-22 05:21

    Maybe I missed it, but has anyone tried a simple generic extension method?

    This works great for me. You can avoid the type cast in your API this way but ultimately it results in a change type operation. This is a good case for programming Roslyn to have the compiler make a GetValue method for you.

        public static void Main()
        {
            int test = MyCSharpWrapperMethod(TestEnum.Test1);
    
            Debug.Assert(test == 1);
        }
    
        public static int MyCSharpWrapperMethod(TestEnum customFlag)
        {
            return MyCPlusPlusMethod(customFlag.GetValue());
        }
    
        public static int MyCPlusPlusMethod(int customFlag)
        {
            // Pretend you made a PInvoke or COM+ call to C++ method that require an integer
            return customFlag;
        }
    
        public enum TestEnum
        {
            Test1 = 1,
            Test2 = 2,
            Test3 = 3
        }
    }
    
    public static class EnumExtensions
    {
        public static T GetValue(this Enum enumeration)
        {
            T result = default(T);
    
            try
            {
                result = (T)Convert.ChangeType(enumeration, typeof(T));
            }
            catch (Exception ex)
            {
                Debug.Assert(false);
                Debug.WriteLine(ex);
            }
    
            return result;
        }
    }
    

提交回复
热议问题