Files
GX.O3.WMS/APP.O3/Shared/Extensions/EnumExtensions.cs
T

83 lines
3.0 KiB
C#
Executable File

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace Opsoft.NetCore.O3App.Shared
{
public static class EnumExtensions
{
public static TResult GetAttribute<TResult>(this Enum source)
where TResult : Attribute
{
var fieldInfo = source.GetType().GetField(source.ToString());
return fieldInfo?.GetCustomAttributes<TResult>(false)?.FirstOrDefault();
}
public static string GetDesc(this Enum source)
{
var descriptionAttribute = GetAttribute<DescriptionAttribute>(source);
return descriptionAttribute?.Description ?? source.ToString();
}
public static string GetDescWithDefault(this Enum source, string defaultDesc = "")
{
var descriptionAttribute = GetAttribute<DescriptionAttribute>(source);
return (descriptionAttribute?.Description ?? defaultDesc).NullOrEmpty2Default(source.ToString());
}
public static string GetDisplay(this Enum source, string defaultDesc = "")
{
var displayAttribute = GetAttribute<DisplayAttribute>(source);
return (displayAttribute?.Display ?? defaultDesc).NullOrEmpty2Default(source.ToString());
}
public static bool IsDefined(this Enum source, object value)
{
return Enum.IsDefined(source.GetType(), value);
}
public static int ToInt32(this Enum value)
{
return Convert.ToInt32(value);
}
}
public static class Enum<E> where E : Enum
{
public static IEnumerable<E> GetValues() => Enum.GetValues(typeof(E)).Cast<E>();
public static IEnumerable<string> GetDescriptions() => GetValues().Select(e => e.GetDesc());
public static IEnumerable<TResult> GetAttributes<TResult>() where TResult : Attribute
=> GetValues().Select(e => e.GetAttribute<TResult>());
public static IEnumerable<KeyValuePair<int, string>> GetValueDescriptionPairs()
=> GetValues().Select(e => new KeyValuePair<int, string>(Convert.ToInt32(e), e.GetDesc()));
public static IEnumerable<KeyValuePair<string, int>> GetDescriptionValuePairs()
=> GetValues().Select(e => new KeyValuePair<string, int>(e.GetDesc(), Convert.ToInt32(e)));
public static IEnumerable<KeyValuePair<E, string>> GetEnumDescriptionPairs()
=> GetValues().Select(e => new KeyValuePair<E, string>(e, e.GetDesc()));
public static IEnumerable<KeyValuePair<E, TResult>> GetEnumAttributePairs<TResult>()
where TResult : Attribute
=> GetValues().Select(e => new KeyValuePair<E, TResult>(e, e.GetAttribute<TResult>()));
public static bool IsDefined(object value)
{
return Enum.IsDefined(typeof(E), value);
}
public static bool NotDefined(object value)
{
return !IsDefined(value);
}
}
}