mirror of
https://github.com/azaion/admin.git
synced 2026-04-22 22:06:33 +00:00
f5e466108a
add ToHash for encryption Key
54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using System.ComponentModel;
|
|
using System.Reflection;
|
|
|
|
namespace Azaion.Common.Extensions;
|
|
|
|
/// <summary>Enum extensions</summary>
|
|
public static class EnumExtensions
|
|
{
|
|
/// <summary>Get all enums with descriptions </summary>
|
|
public static Dictionary<T, string> GetDescriptions<T>() where T : Enum =>
|
|
Enum.GetValues(typeof(T)).Cast<T>()
|
|
.ToDictionary(x => x, x => x.GetEnumAttrib<T, DescriptionAttribute>()?.Description ?? x.ToString());
|
|
|
|
/// <summary>
|
|
/// Get the Description from the DescriptionAttribute.
|
|
/// </summary>
|
|
/// <param name="enumValue"></param>
|
|
/// <returns></returns>
|
|
public static string GetDescription(this Enum enumValue)
|
|
{
|
|
return enumValue.GetType()
|
|
.GetMember(enumValue.ToString())
|
|
.First()
|
|
.GetCustomAttribute<DescriptionAttribute>()?
|
|
.Description ?? enumValue.ToString();
|
|
}
|
|
|
|
/// <summary> Get attribute for enum's member, usually is used for getting Description attribute </summary>
|
|
private static TAttrib GetEnumAttrib<T, TAttrib>(this T value) where T: Enum
|
|
{
|
|
var field = value.GetType().GetField(value.ToString());
|
|
if (field == null)
|
|
return default!;
|
|
|
|
return field.GetCustomAttributes(typeof(TAttrib), false)
|
|
.Cast<TAttrib>()
|
|
.FirstOrDefault()!;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get default value for enum
|
|
/// </summary>
|
|
/// <typeparam name="TEnum"></typeparam>
|
|
/// <returns></returns>
|
|
public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
|
|
{
|
|
var t = typeof(TEnum);
|
|
var attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
|
|
if (attributes is { Length: > 0 })
|
|
return (TEnum)attributes[0].Value!;
|
|
|
|
return default;
|
|
}
|
|
} |