diff --git a/AyCode.Core/Helpers/ConstHelper.cs b/AyCode.Core/Helpers/ConstHelper.cs new file mode 100644 index 0000000..5475988 --- /dev/null +++ b/AyCode.Core/Helpers/ConstHelper.cs @@ -0,0 +1,47 @@ +using System.Reflection; + +namespace AyCode.Core.Helpers; + +public sealed class ConstHelper +{ + private static readonly Dictionary?> ObjectsByNamesByValue = new(); + + public static string NameByValue(int value) where T : class + => GetNameByValue(GetNamesByType(typeof(T).Name) ?? FillNames(), value); + + public static string NameByValue(string typeName, int value) + => GetNameByValue(GetNamesByType(typeName), value); + + + private static string GetNameByValue(IReadOnlyDictionary? namesByValue, int value) + => namesByValue != null && namesByValue.TryGetValue(value, out var fieldName) ? $"[{fieldName}:{value}]" : $"...:{value}]"; + + private static Dictionary? GetNamesByType(string typeName) + { + lock (ObjectsByNamesByValue) + { + if (ObjectsByNamesByValue.TryGetValue(typeName, out var namesByValue) && namesByValue!.Count > 0) + return namesByValue; + } + + return null; + } + + private static Dictionary FillNames() where T : class + { + var objectType = typeof(T); + var namesByValue = new Dictionary(); + + lock (ObjectsByNamesByValue) + { + foreach (var fld in objectType.GetFields().Where(x => (x.Attributes & FieldAttributes.Literal) != 0 && x.FieldType == typeof(int))) + { + namesByValue[(int)fld.GetValue(null)!] = fld.Name; + } + + ObjectsByNamesByValue[objectType.Name] = namesByValue; + } + + return namesByValue; + } +} \ No newline at end of file