AbstractValue.cs 2.6 KB

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