BaseNumberConverter.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // System.ComponentModel.BaseNumberConverter.cs
  3. //
  4. // Authors:
  5. // Andreas Nahr ([email protected])
  6. //
  7. // (C) 2002/2003 Ximian, Inc (http://www.ximian.com)
  8. // (C) 2003 Andreas Nahr
  9. //
  10. using System;
  11. using System.Globalization;
  12. namespace System.ComponentModel
  13. {
  14. public abstract class BaseNumberConverter : TypeConverter
  15. {
  16. internal Type InnerType;
  17. protected BaseNumberConverter()
  18. {
  19. }
  20. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  21. {
  22. if (sourceType == typeof (string))
  23. return true;
  24. return base.CanConvertFrom (context, sourceType);
  25. }
  26. public override bool CanConvertTo(ITypeDescriptorContext context, Type t)
  27. {
  28. if (t == typeof (string))
  29. return true;
  30. return base.CanConvertTo (context, t);
  31. }
  32. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  33. {
  34. if (value.GetType() == typeof (string)) {
  35. try {
  36. return Convert.ChangeType (value, InnerType, culture.NumberFormat);
  37. } catch (Exception e) {
  38. // LAMESPEC MS just seems to pass the internal Exception on to the user
  39. // so it throws a pure Exception here. We should probably throw a
  40. // ArgumentException or something like that
  41. throw e;
  42. }
  43. }
  44. return base.ConvertFrom (context, culture, value);
  45. }
  46. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
  47. object value, Type destinationType)
  48. {
  49. if (value == null)
  50. throw new ArgumentNullException ("value");
  51. if (destinationType == typeof (string) && value.GetType() == InnerType)
  52. return Convert.ChangeType (value, typeof (string), culture.NumberFormat);
  53. return base.ConvertTo (context, culture, value, destinationType);
  54. }
  55. }
  56. }