BindableProperty.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. namespace Blue
  3. {
  4. public class BindableProperty<T>
  5. {
  6. private T _value;
  7. private Action<T> onValueChanged;
  8. public BindableProperty()
  9. {
  10. _value = default(T);
  11. }
  12. public BindableProperty(T defaultValue)
  13. {
  14. _value = defaultValue;
  15. }
  16. public IUnSubscribe Subscribe(Action<T> onPropertyChanged)
  17. {
  18. onValueChanged += onPropertyChanged;
  19. return new BindablePropertyUnSubscribe<T>(this,onPropertyChanged);
  20. }
  21. public void UnSubscribe(Action<T> onPropertyChanged)
  22. {
  23. onValueChanged -= onPropertyChanged;
  24. }
  25. public T Value
  26. {
  27. get => _value;
  28. set
  29. {
  30. if (_value != null)
  31. {
  32. if (!_value.Equals(value))
  33. {
  34. _value = value;
  35. onValueChanged?.Invoke(_value);
  36. }
  37. }
  38. else
  39. {
  40. if (value != null)
  41. {
  42. _value = value;
  43. onValueChanged?.Invoke(_value);
  44. }
  45. }
  46. }
  47. }
  48. public bool IsEmpty()
  49. {
  50. return onValueChanged == null;
  51. }
  52. public override string ToString()
  53. {
  54. if (_value == null)
  55. {
  56. return "null";
  57. }
  58. return _value.ToString();
  59. }
  60. public override int GetHashCode()
  61. {
  62. return _value.GetHashCode();
  63. }
  64. public override bool Equals(object obj)
  65. {
  66. if (obj == null)
  67. {
  68. return false;
  69. }
  70. if (!(obj is BindableProperty<T>))
  71. {
  72. return false;
  73. }
  74. var p2 = (BindableProperty<T>)obj;
  75. return this==p2;
  76. }
  77. public static implicit operator T(BindableProperty<T> b)
  78. {
  79. return b.Value;
  80. }
  81. public static implicit operator BindableProperty<T>(T value)
  82. {
  83. return new BindableProperty<T>(value);
  84. }
  85. }
  86. }