source: extensions/PiwigoLib/PiwigoLib/DTO/Helper/PwgEnumHelper.cs @ 3816

Last change on this file since 3816 was 3816, checked in by bayral, 15 years ago

Initial import

File size: 1.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Reflection;
6using System.ComponentModel;
7using System.Xml.Serialization;
8
9namespace Com.Piwigo.Lib.DTO.Helper
10{
11    public static class PwgEnumHelper<T>
12    {
13        public static string stringValueOf(T value)
14        {
15            FieldInfo fi = value.GetType().GetField(value.ToString());
16            XmlEnumAttribute[] attributes = (XmlEnumAttribute[])fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);
17            if (attributes.Length > 0)
18            {
19                return attributes[0].Name;
20            }
21            else
22            {
23                return value.ToString();
24            }
25        }
26
27        public static T enumValueOf(string value)
28        {
29            Type enumType = typeof(T);
30            Array values = Enum.GetValues(enumType);
31            foreach (T enumValue in values)
32            {
33                if (stringValueOf(enumValue).Equals(value))
34                {
35                    return enumValue;
36                }
37            }
38
39            throw new ArgumentException("The string is not a description or value of the specified enum.");
40        }
41    }
42}
Note: See TracBrowser for help on using the repository browser.