|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
namespace WpfProxy
{
public static class Extensions
{
public static IEnumerable GetEnumDesciptions(this Type enumType)
{
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
ArrayList enumValList = new ArrayList(enumValArray.Length);
foreach (object val in enumValArray)
{
Enum e = (Enum)val;
enumValList.Add(e.GetEnumDescription());
}
return enumValList;
}
public static Enum GetValueFromDescription(Type type, string description)
{
if (!type.IsEnum) throw new InvalidOperationException();
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null)
{
if (attribute.Description == description)
return (Enum)field.GetValue(null);
}
else
{
if (field.Name == description)
return (Enum)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");
// or return default(T);
}
public static string GetEnumDescription(this Enum enumObj)
{
FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
{
return enumObj.ToString();
}
else
{
DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I am a freelance software developer with a variety of different interests. My main area of expertise is Microsoft Office add-ins (Excel/Outlook mostly) but I also develop Windows applications, Access Databases and Excel macros . I develop in VBA, C# and C++. My website
exceladviser.com has articles on Excel, Access, Microsoft Office development, and general Windows programming (WPF, etc.).