39 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			39 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| 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");
 | |
|         }
 | |
|     }
 | |
| }
 |