101 lines
3.0 KiB
C#
101 lines
3.0 KiB
C#
using System.Reflection;
|
||
|
||
namespace BotPages.Core.Messaging;
|
||
|
||
/// <summary>
|
||
/// Описание для кнопки.
|
||
/// </summary>
|
||
[AttributeUsage(AttributeTargets.Field)]
|
||
public class ButtonAttribute : Attribute
|
||
{
|
||
///<inheritdoc/>
|
||
public ButtonAttribute(string label)
|
||
{
|
||
Label = label;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Описание кнопки.
|
||
/// </summary>
|
||
public string Label { get; }
|
||
|
||
/// <summary>
|
||
/// Значение кнопки. Используется в InlineButton.
|
||
/// </summary>
|
||
public string? Value { get; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// Расширение для работы с кнопками.
|
||
/// </summary>
|
||
public static class ButtonExtensions
|
||
{
|
||
private static readonly Dictionary<Type, Dictionary<string, object>> _cacheName = new();
|
||
|
||
/// <summary>
|
||
/// Получить подпись кнопки.
|
||
/// </summary>
|
||
/// <typeparam name="T">Enum тип.</typeparam>
|
||
/// <param name="value">Значение enum.</param>
|
||
/// <returns></returns>
|
||
public static string GetButtonLabel<T>(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<ButtonAttribute>()?.Label ?? fieldName;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Получить значение кнопки.
|
||
/// </summary>
|
||
/// <typeparam name="T">Enum тип.</typeparam>
|
||
/// <param name="value">Значение enum.</param>
|
||
/// <returns></returns>
|
||
public static string GetButtonValue<T>(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<ButtonAttribute>()?.Value ?? fieldName;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Получить значение enum из подписи кнопки.
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="value"></param>
|
||
/// <returns></returns>
|
||
public static T? FromButtonLabel<T>(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<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<ButtonAttribute>();
|
||
|
||
if (attr != null)
|
||
{
|
||
fieldName = attr.Label;
|
||
}
|
||
|
||
map[fieldName] = fieldValue;
|
||
}
|
||
|
||
}
|
||
|
||
return map.TryGetValue(value, out var result) ? (T)result : null;
|
||
}
|
||
} |