2024-09-25 22:20:23 +08:00
|
|
|
|
using Serein.Library.Attributes;
|
|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
|
|
namespace Serein.Library.Utils
|
|
|
|
|
|
{
|
|
|
|
|
|
public static class EnumHelper
|
|
|
|
|
|
{
|
2024-10-07 15:15:18 +08:00
|
|
|
|
public static bool TryConvertEnum<T>(this string value, out T result) where T : struct, Enum
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!string.IsNullOrEmpty(value) && Enum.TryParse(value, true, out T tempResult) && Enum.IsDefined(typeof(T), tempResult))
|
|
|
|
|
|
{
|
|
|
|
|
|
result = tempResult;
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
result = default;
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
2024-09-25 22:20:23 +08:00
|
|
|
|
public static TResult GetBoundValue<TEnum, TResult>(TEnum enumValue, Func<BindValueAttribute, object> valueSelector)
|
|
|
|
|
|
where TEnum : Enum
|
|
|
|
|
|
{
|
|
|
|
|
|
var fieldInfo = typeof(TEnum).GetField(enumValue.ToString());
|
|
|
|
|
|
var attribute = fieldInfo.GetCustomAttribute<BindValueAttribute>();
|
|
|
|
|
|
|
|
|
|
|
|
return attribute != null ? (TResult)valueSelector(attribute) : default;
|
|
|
|
|
|
}
|
2024-09-27 10:30:19 +08:00
|
|
|
|
public static object GetBoundValue(Type enumType,object enumValue, Func<BindValueAttribute, object> valueSelector)
|
|
|
|
|
|
{
|
|
|
|
|
|
var fieldInfo = enumType.GetField(enumValue.ToString());
|
|
|
|
|
|
var attribute = fieldInfo.GetCustomAttribute<BindValueAttribute>();
|
|
|
|
|
|
|
|
|
|
|
|
return attribute != null ? valueSelector(attribute) : default;
|
|
|
|
|
|
}
|
2024-09-25 22:20:23 +08:00
|
|
|
|
|
2024-09-28 23:55:19 +08:00
|
|
|
|
public static TResult GetBoundValue<TEnum, TAttribute, TResult>(TEnum enumValue,
|
|
|
|
|
|
Func<TAttribute, TResult> valueSelector)
|
|
|
|
|
|
where TEnum : Enum
|
|
|
|
|
|
where TAttribute : Attribute
|
|
|
|
|
|
{
|
|
|
|
|
|
var fieldInfo = typeof(TEnum).GetField(enumValue.ToString());
|
|
|
|
|
|
var attribute = fieldInfo.GetCustomAttribute<TAttribute>();
|
|
|
|
|
|
|
|
|
|
|
|
return attribute != null ? valueSelector(attribute) : default;
|
|
|
|
|
|
}
|
2024-09-25 22:20:23 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|