| | | 1 | | namespace Nabs; |
| | | 2 | | |
| | | 3 | | public abstract class ValueObject<T> : IEquatable<T> |
| | | 4 | | where T : ValueObject<T> |
| | | 5 | | { |
| | | 6 | | public abstract IEnumerable<object?> GetEqualityComponents(); |
| | | 7 | | |
| | | 8 | | public bool Equals(T? other) |
| | | 9 | | { |
| | 1 | 10 | | if (other is null) |
| | 1 | 11 | | return false; |
| | | 12 | | |
| | 1 | 13 | | if (ReferenceEquals(this, other)) |
| | 1 | 14 | | return true; |
| | | 15 | | |
| | 1 | 16 | | return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | public override int GetHashCode() |
| | | 20 | | { |
| | 2 | 21 | | return GetEqualityComponents() |
| | 2 | 22 | | .Aggregate(1, (current, obj) => |
| | 2 | 23 | | { |
| | 2 | 24 | | unchecked |
| | 2 | 25 | | { |
| | 2 | 26 | | return current * 23 + (obj?.GetHashCode() ?? 0); |
| | 2 | 27 | | } |
| | 2 | 28 | | }); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public static bool operator ==(ValueObject<T>? left, ValueObject<T>? right) |
| | | 32 | | { |
| | 1 | 33 | | if (left is null && right is null) |
| | 1 | 34 | | return true; |
| | | 35 | | |
| | 1 | 36 | | if (left is null || right is null) |
| | 1 | 37 | | return false; |
| | | 38 | | |
| | 1 | 39 | | return left.Equals(right); |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | public static bool operator !=(ValueObject<T>? left, ValueObject<T>? right) |
| | | 43 | | { |
| | 1 | 44 | | return !(left == right); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | public override bool Equals(object? obj) |
| | | 48 | | { |
| | 1 | 49 | | if (obj == null || obj.GetType() != GetType()) |
| | 1 | 50 | | return false; |
| | | 51 | | |
| | 1 | 52 | | var other = (T)obj; |
| | 1 | 53 | | return Equals(other); |
| | | 54 | | } |
| | | 55 | | } |