using System.Reflection; namespace BotPages.Core.Messaging; /// /// Описание для кнопки. /// [AttributeUsage(AttributeTargets.Field)] public class ButtonAttribute : Attribute { /// public ButtonAttribute(string label) { Label = label; } /// /// Описание кнопки. /// public string Label { get; } /// /// Значение кнопки. Используется в InlineButton. /// public string? Value { get; } } /// /// Расширение для работы с кнопками. /// public static class ButtonExtensions { private static readonly Dictionary> _cacheName = new(); /// /// Получить подпись кнопки. /// /// Enum тип. /// Значение enum. /// public static string GetButtonLabel(this T value) where T : Enum { var fieldName = value.ToString(); var type = value.GetType(); var field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static); return field?.GetCustomAttribute()?.Label ?? fieldName; } /// /// Получить значение кнопки. /// /// Enum тип. /// Значение enum. /// public static string GetButtonValue(this T value) where T : Enum { var fieldName = value.ToString(); var type = value.GetType(); var field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static); return field?.GetCustomAttribute()?.Value ?? fieldName; } /// /// Получить значение enum из подписи кнопки. /// /// /// /// public static T? FromButtonLabel(string? value) where T : struct, Enum { if (value == null) return null; var type = typeof(T); if (!_cacheName.TryGetValue(type, out var map)) { map = new Dictionary(); 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(); if (attr != null) { fieldName = attr.Label; } map[fieldName] = fieldValue; } } return map.TryGetValue(value, out var result) ? (T)result : null; } }