Created
April 11, 2013 19:31
-
-
Save seburgi/5366479 to your computer and use it in GitHub Desktop.
Generates a hashcode for simple objects that depends on its contents.
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 class HashCodeGenerator<T> | |
{ | |
private readonly List<Func<T, object>> _getters = new List<Func<T, object>>(); | |
public HashCodeGenerator() | |
{ | |
PropertyInfo[] properties = typeof(T).GetProperties(); | |
foreach (var p in properties) | |
{ | |
Func<T, object> getter = GetValueGetter<T>(p); | |
_getters.Add(getter); | |
} | |
} | |
public int Generate(T o) | |
{ | |
int hashCode = 0; | |
foreach (var getter in _getters) | |
{ | |
object value = getter(o); | |
hashCode = (hashCode * 397) ^ (value != null ? value.GetHashCode() : 0); | |
} | |
return hashCode; | |
} | |
private static Func<T, object> GetValueGetter<T>(PropertyInfo propertyInfo) | |
{ | |
ParameterExpression instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); | |
MemberExpression property = Expression.Property(instance, propertyInfo); | |
UnaryExpression convert = Expression.TypeAs(property, typeof(object)); | |
return Expression.Lambda<Func<T, object>>(convert, instance).Compile(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment