Files
BotPages/BotPages.Core/Pages/ActionExtensions.cs
FrigaT 4aff8edbcd
All checks were successful
CI / build-test (push) Successful in 31s
Release / pack-and-publish (release) Successful in 1m12s
Доработан менеджер состояний.
2025-12-03 07:15:46 +03:00

49 lines
1.4 KiB
C#

using System.Reflection;
namespace BotPages.Core
{
public static class ActionExtensions
{
private static readonly Dictionary<Type, Dictionary<string, object>> _cache = new();
public static string GetActionLabel<T>(this T value)
where T : Enum
{
var fieldName = value.ToString();
var field = typeof(T).GetField(fieldName, BindingFlags.Public | BindingFlags.Static);
return field?.GetCustomAttribute<ActionAttribute>()?.Label ?? fieldName;
}
public static T? FromActionLabel<T>(string? value) where T : struct, Enum
{
if (value == null) return null;
var type = typeof(T);
if (!_cache.TryGetValue(type, out var map))
{
map = new Dictionary<string, object>();
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields)
{
var fieldValue = field.GetValue(null)!;
var fieldName = field.Name;
var attr = field.GetCustomAttribute<ActionAttribute>();
if (attr != null)
{
fieldName = attr.Label;
}
map[fieldName] = fieldValue;
}
}
return map.TryGetValue(value, out var result) ? (T)result : null;
}
}
}