-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathValueObject.cs
89 lines (64 loc) · 2.08 KB
/
ValueObject.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//From Pluralsight Domain-Driven Design Fundamentals Course (bit.ly/PS-DDD)
using System;
using System.Collections.Generic;
using System.Reflection;
//this base class comes from Jimmy Bogard
//http://grabbagoft.blogspot.com/2007/06/generic-value-object-equality.html
namespace Shared {
public abstract class ValueObject<T> : IEquatable<T>
where T : ValueObject<T> {
public virtual bool Equals(T other) {
if (other == null)
return false;
Type t = GetType();
Type otherType = other.GetType();
if (t != otherType)
return false;
FieldInfo[] fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (FieldInfo field in fields) {
object value1 = field.GetValue(other);
object value2 = field.GetValue(this);
if (value1 == null) {
if (value2 != null)
return false;
}
else if (!value1.Equals(value2))
return false;
}
return true;
}
public override bool Equals(object obj) {
if (obj == null)
return false;
var other = obj as T;
return Equals(other);
}
public override int GetHashCode() {
IEnumerable<FieldInfo> fields = GetFields();
int startValue = 17;
int multiplier = 59;
int hashCode = startValue;
foreach (FieldInfo field in fields) {
object value = field.GetValue(this);
if (value != null)
hashCode = hashCode*multiplier + value.GetHashCode();
}
return hashCode;
}
private IEnumerable<FieldInfo> GetFields() {
Type t = GetType();
var fields = new List<FieldInfo>();
while (t != typeof (object)) {
fields.AddRange(t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));
t = t.BaseType;
}
return fields;
}
public static bool operator ==(ValueObject<T> x, ValueObject<T> y) {
return x.Equals(y);
}
public static bool operator !=(ValueObject<T> x, ValueObject<T> y) {
return !(x == y);
}
}
}