Files
BQP/srcs/RobotNet10/Shared/RobotNet.VDA5050/EnumHelper.cs
2026-07-13 09:25:40 +07:00

59 lines
1.8 KiB
C#

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<JsonStringEnumMemberNameAttribute>();
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<JsonStringEnumMemberNameAttribute>();
return attribute?.Name ?? enumValue.ToString();
}
private static readonly Dictionary<string, ActionType> Cache = BuildCache();
private static Dictionary<string, ActionType> BuildCache()
{
var result = new Dictionary<string, ActionType>();
foreach (ActionType value in Enum.GetValues<ActionType>())
{
var field = typeof(ActionType).GetField(value.ToString());
var attribute = field?.GetCustomAttribute<JsonStringEnumMemberNameAttribute>();
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);
}
}