1 | using System; |
---|
2 | using System.Reflection; |
---|
3 | using System.Xml.Serialization; |
---|
4 | using System.Collections.Generic; |
---|
5 | |
---|
6 | namespace Com.Piwigo.Lib.DTO.Helper |
---|
7 | { |
---|
8 | public static class PwgEnumHelper<T> |
---|
9 | { |
---|
10 | static PwgEnumHelper() |
---|
11 | { |
---|
12 | if (!typeof(T).IsEnum) { |
---|
13 | throw new ArgumentException(String.Format("PwgEnumHelper<T>(): The type {0} is not a enum.", typeof(T).Name)); |
---|
14 | } |
---|
15 | } |
---|
16 | |
---|
17 | internal static String StringValueOf(T value) |
---|
18 | { |
---|
19 | FieldInfo fi = value.GetType().GetField(value.ToString()); |
---|
20 | XmlEnumAttribute[] attributes = (XmlEnumAttribute[])fi.GetCustomAttributes(typeof(XmlEnumAttribute), false); |
---|
21 | if (attributes.Length > 0) |
---|
22 | { |
---|
23 | return attributes[0].Name; |
---|
24 | } |
---|
25 | else |
---|
26 | { |
---|
27 | return value.ToString(); |
---|
28 | } |
---|
29 | } |
---|
30 | |
---|
31 | internal static T enumValueOf(String value) |
---|
32 | { |
---|
33 | Type enumType = typeof(T); |
---|
34 | Array values = Enum.GetValues(enumType); |
---|
35 | foreach (T enumValue in values) |
---|
36 | { |
---|
37 | if (StringValueOf(enumValue).Equals(value)) |
---|
38 | { |
---|
39 | return enumValue; |
---|
40 | } |
---|
41 | } |
---|
42 | |
---|
43 | throw new ArgumentException(String.Format("PwgEnumHelper<{0}>.enumValueOf({1}): The String is not a description or value of the specified enum.", typeof(T).Name, value)); |
---|
44 | } |
---|
45 | |
---|
46 | public static List<KeyValuePair<T, String>> buildChoiceList() |
---|
47 | { |
---|
48 | List<KeyValuePair<T, String>> lst = new List<KeyValuePair<T, String>>(); |
---|
49 | |
---|
50 | foreach (T item in Enum.GetValues(typeof(T))) |
---|
51 | { |
---|
52 | lst.Add(new KeyValuePair<T, String>(item, StringValueOf(item))); |
---|
53 | } |
---|
54 | |
---|
55 | return lst; |
---|
56 | } |
---|
57 | } |
---|
58 | } |
---|