Skip to content

Instantly share code, notes, and snippets.

@sakapon

sakapon/EquatableObject.cs

Last active Aug 31, 2020
Embed
What would you like to do?
OperatorsSample/VectorEq class
using System;
using System.Reflection;
namespace OperatorsLib.Classes
{
public abstract class EquatableObject
{
// ValueType と同様に、すべてのフィールドで等価性を評価します。
public override bool Equals(object obj)
{
var type = GetType();
if (type != obj?.GetType()) return false;
foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
if (!Equals(field.GetValue(this), field.GetValue(obj))) return false;
return true;
}
public override int GetHashCode()
{
HashCode hc = default;
foreach (var field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
hc.Add(field.GetValue(this));
return hc.ToHashCode();
}
}
}
namespace OperatorsLib.Classes
{
public class VectorEq : EquatableObject
{
public double X { get; }
public double Y { get; }
public VectorEq(double x, double y) => (X, Y) = (x, y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment