using RobotNet.VDA5050.Type; using System.Reflection; using System.Text.Json.Serialization; namespace RobotNet.VDA5050; public static class EnumHelper { public static string ToJsonString(this VDA5050Topic enumValue) { var type = enumValue.GetType(); var memberInfo = type.GetMember(enumValue.ToString()).FirstOrDefault(); if (memberInfo == null) return enumValue.ToString(); var attribute = memberInfo.GetCustomAttribute(); return attribute?.Name ?? enumValue.ToString(); } public static string ToJsonString(this Enum enumValue) { var type = enumValue.GetType(); var memberInfo = type.GetMember(enumValue.ToString()).FirstOrDefault(); if (memberInfo == null) return enumValue.ToString(); var attribute = memberInfo.GetCustomAttribute(); return attribute?.Name ?? enumValue.ToString(); } private static readonly Dictionary Cache = BuildCache(); private static Dictionary BuildCache() { var result = new Dictionary(); foreach (ActionType value in Enum.GetValues()) { var field = typeof(ActionType).GetField(value.ToString()); var attribute = field?.GetCustomAttribute(); if (attribute != null) { result[attribute.Name] = value; } // Cũng thêm tên enum gốc để hỗ trợ cả hai result[value.ToString()] = value; } return result; } public static bool TryParse(string value, out ActionType result) { return Cache.TryGetValue(value, out result); } }