Доработан менеджер состояний.
This commit is contained in:
48
BotPages.Core/Pages/ActionExtensions.cs
Normal file
48
BotPages.Core/Pages/ActionExtensions.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user