You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel/Services/Extensions/EnumExtensions.cs

53 lines
2.0 KiB

6 years ago
using System;
using System.ComponentModel;
namespace ZeroLevel
{
public static class EnumExtensions
{
/// <summary>
/// Gets an attribute on an enum field value
/// </summary>
/// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
/// <param name="enumVal">The enum value</param>
/// <returns>The attribute of type T that exists on the enum value</returns>
/// <example>string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute/>().Description;</example>
public static T GetAttributeOfType<T>(this Enum enumVal)
where T : Attribute
{
var type = enumVal.GetType();
var memInfo = type.GetMember(enumVal.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
5 months ago
return ((attributes.Length > 0) ? (T)attributes[0] : null)!;
6 years ago
}
public static string Description(this Enum enumVal)
{
var attr = enumVal.GetAttributeOfType<DescriptionAttribute>();
5 months ago
return attr?.Description!;
6 years ago
}
public static T GetValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum) throw new InvalidOperationException();
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
5 months ago
if (attribute != null!)
6 years ago
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if (field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", nameof(description));
5 months ago
// or return default(T)!;
6 years ago
}
}
}

Powered by TurnKey Linux.