Generic enum to int
Редактировал(а) Alexandr Fokin 2024/09/10 13:02
How do I cast a generic enum to int? https://stackoverflow.com/questions/16960555/how-do-i-cast-a-generic-enum-to-int | |
public static class EnumHelper { /// <summary> /// Использует ExpressionTree для производительности (no boxing object) /// </summary> public static int EnumToInt<T>(this T value) where T : struct, Enum => EnumHelper.GenericEnum<T>.EnumToInt(value); private static class GenericEnum<T> where T : struct, Enum { public static readonly Func<T, int> EnumToInt; static GenericEnum() { { var inputParameter = Expression.Parameter(typeof(T)); var body = Expression.Convert(inputParameter, typeof(int)); var lambda = Expression.Lambda<Func<T, int>>(body, inputParameter); EnumToInt = lambda.Compile(); } } } } |