AbstractValue.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. namespace Quadarax.Foundation.Core.QConsole.Value
  3. {
  4. public abstract class AbstractValue
  5. {
  6. private object _value;
  7. /// <summary>
  8. /// Defines if value is set. Not null.
  9. /// </summary>
  10. public bool HasValue => _value != null;
  11. /// <summary>
  12. /// Returns underlying system value type.
  13. /// </summary>
  14. public Type ValueType { get; }
  15. public AbstractValue()
  16. {
  17. Reset();
  18. }
  19. public AbstractValue(Type valueType, object value) : this(valueType)
  20. {
  21. _value = value;
  22. }
  23. protected AbstractValue(Type valueType)
  24. {
  25. ValueType = valueType ?? throw new ArgumentNullException(nameof(valueType));
  26. }
  27. protected abstract object ConvertStringToValue(string valueAsString);
  28. public abstract string AsString();
  29. public void Set(string valueAsString)
  30. {
  31. if (string.IsNullOrEmpty(valueAsString))
  32. {
  33. Reset();
  34. return;
  35. }
  36. Set(ConvertStringToValue(valueAsString));
  37. }
  38. public virtual void Set(object value)
  39. {
  40. _value = value;
  41. }
  42. public object Get()
  43. {
  44. return _value;
  45. }
  46. public void Reset()
  47. {
  48. _value = null;
  49. }
  50. public static AbstractValue Create(TypeValuesEnum typeValue)
  51. {
  52. switch (typeValue)
  53. {
  54. case TypeValuesEnum.Bool:
  55. return new BoolValue();
  56. case TypeValuesEnum.Date:
  57. return new DateValue();
  58. case TypeValuesEnum.DateTime:
  59. return new DateTimeValue();
  60. case TypeValuesEnum.Decimal:
  61. return new DecimalValue();
  62. case TypeValuesEnum.Guid:
  63. return new GuidValue();
  64. case TypeValuesEnum.Integer:
  65. return new IntegerValue();
  66. case TypeValuesEnum.String:
  67. return new StringValue();
  68. case TypeValuesEnum.Time:
  69. return new TimeValue();
  70. case TypeValuesEnum.TimeSpan:
  71. return new TimeSpanValue();
  72. default:
  73. throw new NotSupportedException($"Unsupported argument value '{typeValue}'");
  74. }
  75. }
  76. public override string ToString()
  77. {
  78. return AsString();
  79. }
  80. }
  81. }