Moved Object Model to separate project
This commit is contained in:
38
Filtration.ObjectModel/Extensions/EnumHelper.cs
Normal file
38
Filtration.ObjectModel/Extensions/EnumHelper.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Filtration.ObjectModel.Extensions
|
||||
{
|
||||
public static class EnumHelper
|
||||
{
|
||||
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);
|
||||
return (attributes.Length > 0) ? (T)attributes[0] : null;
|
||||
}
|
||||
|
||||
public static string GetAttributeDescription(this Enum enumValue)
|
||||
{
|
||||
var attribute = enumValue.GetAttributeOfType<DescriptionAttribute>();
|
||||
|
||||
return attribute == null ? String.Empty : attribute.Description;
|
||||
}
|
||||
|
||||
public static T GetEnumValueFromDescription<T>(string description)
|
||||
{
|
||||
var fis = typeof(T).GetFields();
|
||||
|
||||
foreach (var fi in fis)
|
||||
{
|
||||
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
|
||||
|
||||
if (attributes.Length > 0 && attributes[0].Description == description)
|
||||
return (T)Enum.Parse(typeof(T), fi.Name);
|
||||
}
|
||||
|
||||
throw new Exception("Not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user