Created
September 1, 2015 16:24
-
-
Save DavidBrower/86b663021f909801a480 to your computer and use it in GitHub Desktop.
ValueObject Base Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class ValueObject<T> : IEquatable<T> where T : ValueObject<T> | |
{ | |
private List<PropertyInfo> Properties { get; } | |
protected ValueObject() | |
{ | |
Properties = new List<PropertyInfo>(); | |
} | |
public override Boolean Equals(object obj) | |
{ | |
if (ReferenceEquals(null, obj)) return false; | |
if (obj.GetType() != GetType()) return false; | |
return Equals(obj as T); | |
} | |
public bool Equals(T other) | |
{ | |
if (ReferenceEquals(null, other)) return false; | |
if (ReferenceEquals(this, other)) return true; | |
foreach (var property in Properties) | |
{ | |
var myValue = property.GetValue(this, null); | |
var otherValue = property.GetValue(other, null); | |
if (null == myValue || null == otherValue) return false; | |
if (false == myValue.Equals(otherValue)) return false; | |
} | |
return true; | |
} | |
public override int GetHashCode() | |
{ | |
var hashCode = 36; | |
foreach (var property in Properties) | |
{ | |
var propertyValue = property.GetValue(this, null); | |
if (null == propertyValue) | |
continue; | |
hashCode = hashCode ^ propertyValue.GetHashCode(); | |
} | |
return hashCode; | |
} | |
public override string ToString() | |
{ | |
var stringBuilder = new StringBuilder(); | |
foreach (var property in Properties) | |
{ | |
var propertyValue = property.GetValue(this, null); | |
if (null == propertyValue) | |
continue; | |
stringBuilder.Append(propertyValue.ToString()); | |
} | |
return stringBuilder.ToString(); | |
} | |
protected void RegisterProperty(Expression<Func<T, object>> expression) | |
{ | |
if (expression == null) throw new ArgumentNullException(nameof(expression)); | |
MemberExpression memberExpression; | |
if (ExpressionType.Convert == expression.Body.NodeType) | |
{ | |
var body = (UnaryExpression)expression.Body; | |
memberExpression = body.Operand as MemberExpression; | |
} | |
else | |
{ | |
memberExpression = expression.Body as MemberExpression; | |
} | |
if (null == memberExpression) | |
{ | |
throw new InvalidOperationException("InvalidMemberExpression"); | |
} | |
Properties.Add(memberExpression.Member as PropertyInfo); | |
} | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@DavidBrower quick question: where/how is this method used please?