C# non-boxing conversion of generic enum to int?

前端 未结 9 1948
庸人自扰
庸人自扰 2020-12-04 07:31

Given a generic parameter TEnum which always will be an enum type, is there any way to cast from TEnum to int without boxing/unboxing?

See this example code. This w

9条回答
  •  执念已碎
    2020-12-04 07:57

    I know I'm way late to the party, but if you just need to do a safe cast like this you can use the following using Delegate.CreateDelegate:

    public static int Identity(int x){return x;}
    // later on..
    Func identity = Identity;
    Delegate.CreateDelegate(typeof(Func),identity.Method) as Func
    

    now without writing Reflection.Emit or expression trees you have a method that will convert int to enum without boxing or unboxing. Note that TEnum here must have an underlying type of int or this will throw an exception saying it cannot be bound.

    Edit: Another method that works too and might be a little less to write...

    Func converter = EqualityComparer.Default.GetHashCode;
    

    This works to convert your 32bit or less enum from a TEnum to an int. Not the other way around. In .Net 3.5+, the EnumEqualityComparer is optimized to basically turn this into a return (int)value;

    You are paying the overhead of using a delegate, but it certainly will be better than boxing.

提交回复
热议问题