sharee.bike-App/TINKLib/Model/EnumExtensions.cs

35 lines
865 B
C#
Raw Normal View History

2022-08-30 15:42:25 +02:00
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace TINK.Model
{
2022-09-06 16:08:19 +02:00
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enu)
{
var attr = GetDisplayAttribute(enu);
return attr != null ? attr.Name : enu.ToString();
}
2022-08-30 15:42:25 +02:00
2022-09-06 16:08:19 +02:00
public static string GetDescription(this Enum enu)
{
var attr = GetDisplayAttribute(enu);
return attr != null ? attr.Description : enu.ToString();
}
2022-08-30 15:42:25 +02:00
2022-09-06 16:08:19 +02:00
private static DisplayAttribute GetDisplayAttribute(object value)
{
Type type = value?.GetType() ?? typeof(object);
if (!type.IsEnum)
{
throw new ArgumentException(string.Format("Type {0} is not an enum", type));
}
2022-08-30 15:42:25 +02:00
2022-09-06 16:08:19 +02:00
// Get the enum field.
var field = type.GetField(value.ToString());
return field == null ? null : field.GetCustomAttribute<DisplayAttribute>();
}
}
2022-08-30 15:42:25 +02:00
}