Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
EnumValues.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Globalization;
5 using System.Linq;
6 
7 namespace SiliconStudio.Presentation.ValueConverters
8 {
9  /// <summary>
10  /// This converter will convert a <see cref="Type"/> to an enumerable of <see cref="Enum"/> values, assuming the given type represents an enum or
11  /// a nullable enum. Enums with <see cref="FlagsAttribute"/> are supported as well.
12  /// </summary>
13  public class EnumValues : OneWayValueConverter<EnumValues>
14  {
15  /// <inheritdoc/>
16  public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
17  {
18  var enumType = value as Type;
19  if (enumType == null)
20  return null;
21 
22  if (!enumType.IsEnum)
23  {
24  enumType = Nullable.GetUnderlyingType(enumType);
25  if (enumType == null || !enumType.IsEnum)
26  return null;
27  }
28  var query = Enum.GetValues(enumType).Cast<object>();
29 
30  if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
31  {
32  object enumZero = GetEnumZero(enumType);
33  if (Enum.IsDefined(enumType, enumZero))
34  {
35  query = query.Where(x => Equals(x, enumZero) == false);
36  }
37  }
38 
39  return query.Distinct().ToArray();
40  }
41 
42  private static object GetEnumZero(Type enumType)
43  {
44  if (enumType == null)
45  throw new ArgumentNullException("enumType");
46 
47  Type underlyingType = Enum.GetUnderlyingType(enumType);
48 
49  if (underlyingType == null)
50  throw new ArgumentNullException("enumType");
51 
52  if (underlyingType == typeof(byte))
53  return Enum.ToObject(enumType, (byte)0);
54  if (underlyingType == typeof(sbyte))
55  return Enum.ToObject(enumType, (sbyte)0);
56  if (underlyingType == typeof(short))
57  return Enum.ToObject(enumType, (short)0);
58  if (underlyingType == typeof(ushort))
59  return Enum.ToObject(enumType, (ushort)0);
60  if (underlyingType == typeof(int))
61  return Enum.ToObject(enumType, 0);
62  if (underlyingType == typeof(uint))
63  return Enum.ToObject(enumType, (uint)0);
64  if (underlyingType == typeof(long))
65  return Enum.ToObject(enumType, (long)0);
66  if (underlyingType == typeof(ulong))
67  return Enum.ToObject(enumType, (ulong)0);
68 
69  throw new ArgumentException(string.Format("Unknown enum underlying type '{0}'", underlyingType.FullName));
70  }
71  }
72 }
This converter will convert a Type to an enumerable of Enum values, assuming the given type represent...
Definition: EnumValues.cs:13
override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
Definition: EnumValues.cs:16