75 lines
2.3 KiB
C#
75 lines
2.3 KiB
C#
|
|
using LMS.Common.Attributes;
|
|||
|
|
using static LMS.Common.Enums.PermissionEnum;
|
|||
|
|
|
|||
|
|
namespace LMS.Tools
|
|||
|
|
{
|
|||
|
|
public static class EnumExtensions
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 判断是否为有效的权限类型
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="value"></param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static bool IsValidPermissionType(Type enumType, object value)
|
|||
|
|
{
|
|||
|
|
if (enumType == null || !enumType.IsEnum)
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (value == null)
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 处理整数类型
|
|||
|
|
if (value is int intValue)
|
|||
|
|
{
|
|||
|
|
return Enum.IsDefined(enumType, intValue);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 处理字符串类型
|
|||
|
|
if (value is string stringValue)
|
|||
|
|
{
|
|||
|
|
return Enum.TryParse(enumType, stringValue, true, out _);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 如果不是整数或字符串,尝试转换为枚举底层类型
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var underlyingType = Enum.GetUnderlyingType(enumType);
|
|||
|
|
var convertedValue = Convert.ChangeType(value, underlyingType);
|
|||
|
|
return Enum.IsDefined(enumType, convertedValue);
|
|||
|
|
}
|
|||
|
|
catch
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 获取对应的枚举的描述
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="value"></param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static string GetDescription(this Enum value)
|
|||
|
|
{
|
|||
|
|
var field = value.GetType().GetField(value.ToString());
|
|||
|
|
var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
|
|||
|
|
return attribute == null ? value.ToString() : attribute.Description;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 获取对应的枚举的结果
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="value"></param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static string GetResult(this Enum value)
|
|||
|
|
{
|
|||
|
|
var field = value.GetType().GetField(value.ToString());
|
|||
|
|
var attribute = Attribute.GetCustomAttribute(field, typeof(ResultAttribute)) as ResultAttribute;
|
|||
|
|
return attribute == null ? value.ToString() : attribute.Result;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|