Initial commit
This commit is contained in:
58
srcs/RobotNet10/Shared/RobotNet.VDA5050/EnumHelper.cs
Normal file
58
srcs/RobotNet10/Shared/RobotNet.VDA5050/EnumHelper.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user