EnumConverter.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // System.ComponentModel.EnumConverter
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Globalization;
  11. namespace System.ComponentModel
  12. {
  13. public class EnumConverter : TypeConverter
  14. {
  15. private Type type;
  16. private StandardValuesCollection stdValues;
  17. public EnumConverter (Type type)
  18. {
  19. this.type = type;
  20. }
  21. [MonoTODO]
  22. public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
  23. {
  24. return base.CanConvertTo (context, destinationType);
  25. }
  26. [MonoTODO]
  27. public override object ConvertTo (ITypeDescriptorContext context,
  28. CultureInfo culture,
  29. object value,
  30. Type destinationType)
  31. {
  32. if (destinationType == typeof (string))
  33. return value.ToString ();
  34. return base.ConvertTo (context, culture, value, destinationType);
  35. }
  36. public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
  37. {
  38. if (sourceType == typeof (string))
  39. return true;
  40. return base.CanConvertFrom (context, sourceType);
  41. }
  42. public override object ConvertFrom (ITypeDescriptorContext context,
  43. CultureInfo culture,
  44. object value)
  45. {
  46. string val = value as string;
  47. if (val == null)
  48. return base.ConvertFrom(context, culture, value);
  49. string [] subValues = val.Split (new char [] {','});
  50. long longResult = 0;
  51. foreach (string s in subValues)
  52. longResult |= (long) Enum.Parse (type, s, true);
  53. return Enum.ToObject (type, longResult);
  54. }
  55. public override bool IsValid (ITypeDescriptorContext context, object value)
  56. {
  57. return Enum.IsDefined (type, value);
  58. }
  59. public override bool GetStandardValuesSupported (ITypeDescriptorContext context)
  60. {
  61. return true;
  62. }
  63. public override bool GetStandardValuesExclusive (ITypeDescriptorContext context)
  64. {
  65. return !(type.IsDefined (typeof (FlagsAttribute), false));
  66. }
  67. public override StandardValuesCollection GetStandardValues (ITypeDescriptorContext context)
  68. {
  69. if (stdValues == null) {
  70. Array values = Enum.GetValues (type);
  71. Array.Sort (values);
  72. stdValues = new StandardValuesCollection (values);
  73. }
  74. return stdValues;
  75. }
  76. }
  77. }