49 lines
1.4 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|