2022-09-08 08:04:32 -07:00

71 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace Church.Net.Utility
{
public static class EnumHelper
{
public static string EnumToDescriptionString(this Enum val)
{
//pull out first value in case of flag enumeration
var firstValue = val.ToString().Split(',').Select(s => s.Trim()).First();
IEnumerable<DescriptionAttribute> attributes = val
.GetType()
.GetField(firstValue)
.GetCustomAttributes<DescriptionAttribute>(false);
return true == attributes?.Any() ? attributes.First().Description : val.ToString();
}
public static T GetEnumValueFromDescription<T>(string description) where T : struct
{
object value = GetEnumValueFromDescription(typeof(T), description);
return value is null ? default : (T)value;
}
public static object GetEnumValueFromDescription(Type type, string description)
{
if (type is null) return null;
if (!type.IsEnum)
{
if (type.IsNullableEnum())
{
type = Nullable.GetUnderlyingType(type);
}
else
{
throw new ArgumentException();
}
}
FieldInfo field = type.GetFields()
.FirstOrDefault(f => f.GetCustomAttributes<DescriptionAttribute>(false)
.FirstOrDefault(a => a.Description == description) != null
)
;
return field == null ? null : Enum.ToObject(type, field?.GetRawConstantValue());
return field?.GetRawConstantValue();
}
public static bool IsNullableEnum(this Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return (u != null) && u.IsEnum;
}
public static TEnum GetDefaultEnumValue<TEnum>() where TEnum : struct
{
return (TEnum)GetDefaultEnumValue(typeof(TEnum));
}
public static object GetDefaultEnumValue(Type type)
{
if (type is null) return null;
IEnumerable<DefaultValueAttribute> attributes = type.GetCustomAttributes<DefaultValueAttribute>(false);
return attributes?.FirstOrDefault()?.Value;
}
}
}