Исходный код вики Generic enum to int

Редактировал(а) Alexandr Fokin 2024/09/10 13:02

Скрыть последних авторов
Alexandr Fokin 1.1 1 |(% style="width:103px" %) |(% style="width:1334px" %)
2 |(% style="width:103px" %) |(% style="width:1334px" %)How do I cast a generic enum to int?
3 [[https:~~/~~/stackoverflow.com/questions/16960555/how-do-i-cast-a-generic-enum-to-int>>url:https://stackoverflow.com/questions/16960555/how-do-i-cast-a-generic-enum-to-int]]
4 |(% style="width:103px" %) |(% style="width:1334px" %){{code language="c#"}}public static class EnumHelper
5 {
6 /// <summary>
7 /// Использует ExpressionTree для производительности (no boxing object)
8 /// </summary>
9 public static int EnumToInt<T>(this T value)
10 where T : struct, Enum
11 => EnumHelper.GenericEnum<T>.EnumToInt(value);
12
13 private static class GenericEnum<T>
14 where T : struct, Enum
15 {
16 public static readonly Func<T, int> EnumToInt;
17
18 static GenericEnum()
19 {
20 {
21 var inputParameter = Expression.Parameter(typeof(T));
22 var body = Expression.Convert(inputParameter, typeof(int));
23 var lambda = Expression.Lambda<Func<T, int>>(body, inputParameter);
24 EnumToInt = lambda.Compile();
25 }
26 }
27 }
28 }{{/code}}
29
30