using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ObjectEqualsTest
{
public class Point
{
public Int32 x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override bool Equals(object obj)
{
if (obj.GetType()!= this.GetType())
return false;
FieldInfo[] thisFieldsInfo = this.GetType().GetFields();
FieldInfo[] objFieldsInfo = obj.GetType().GetFields();
if (thisFieldsInfo.Length != objFieldsInfo.Length)
return false;
else
{
for (int i = 0; i < thisFieldsInfo.Length; i++)
{
if ((thisFieldsInfo[i].GetType() != objFieldsInfo[i].GetType()) &&
(thisFieldsInfo[i].Name != objFieldsInfo[i].Name)&&
(thisFieldsInfo[i].GetValue(this) != objFieldsInfo[i].GetValue(obj)))
{
Console.WriteLine(thisFieldsInfo[i].GetValue(this) + " " + objFieldsInfo[i].GetValue(obj));
return false;
}
else
{
Console.WriteLine(thisFieldsInfo[i].GetValue(this) + " " + objFieldsInfo[i].GetValue(obj));
if (i == thisFieldsInfo.Length - 1)
return true;
}
}
}
return false;
}
public override int GetHashCode()
{
var hashCode = 1502939027;
hashCode = hashCode * -1521134295 + x.GetHashCode();
hashCode = hashCode * -1521134295 + y.GetHashCode();
return hashCode;
}
}
class Program
{
static void Main(string[] args)
{
Point x1 = new Point(1, 3);
Point x2 = new Point(1, 2);
Console.WriteLine(x1.Equals(x2));
Console.ReadKey();
}
}
}
Есть вот такой код для сравнения двух объектов. Проблема в том, что if() с проверками на тип, имя и значение полей работает как-то неадекватно. Если закомментировать первые две проверки - всегда выдаёт false, если разкомментирую первую и вторую проверки - всегда будет true, но ведь проверка значения выдаёт false, wtf. Не могу понять, что я не так делаю.