Skip to content

Instantly share code, notes, and snippets.

@mfakane
Created August 18, 2011 21:02
Show Gist options
  • Save mfakane/1155193 to your computer and use it in GitHub Desktop.
Save mfakane/1155193 to your computer and use it in GitHub Desktop.
かんたん Equatable
using System;
using System.Linq;
namespace Ignition
{
public static class Equatable
{
public static int GetMemberwiseHashCode(object obj)
{
return obj.GetType().GetProperties()
.Where(_ => _.CanRead && !_.GetIndexParameters().Any())
.Select(_ => _.GetValue(obj, null))
.Select(_ => _ == null ? 0 : _.GetHashCode())
.Aggregate((from, i) => from ^ i);
}
public static bool MemberwiseEquals<T>(this IEquatable<T> self, T target)
{
var props = typeof(T).GetProperties()
.Where(_ => _.CanRead && !_.GetIndexParameters().Any());
return target != null
&& self.GetType().IsAssignableFrom(target.GetType())
&& props.Select(_ => _.GetValue(self, null))
.SequenceEqual(props.Select(_ => _.GetValue(target, null)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment