C# 当对象实现Equals时,Newtonsoft.Json序列化的行为很奇怪
我有下面的例子C# 当对象实现Equals时,Newtonsoft.Json序列化的行为很奇怪,c#,json,serialization,json.net,C#,Json,Serialization,Json.net,我有下面的例子 public class Main { public Student Student { get; set; } public override bool Equals(object obj) { if (this.GetType() != obj.GetType()) throw new Exception(); return Student.Age == ((Student)obj).Age; }
public class Main
{
public Student Student { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return Student.Age == ((Student)obj).Age;
}
}
public class Student
{
public int Age { get; set; }
public Name Name { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return Age == ((Student)obj).Age;
}
}
public class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return FirstName == ((Name)obj).FirstName && LastName == ((Name)obj).LastName;
}
}
当我尝试序列化时
JsonConvert.SerializeObject(new Main{ ... });
我在主类型的Equals方法中得到了不同的类型,我会在另一个Equals方法中假设不同的类型
我得到的类型是
this.GetType() // => Main
obj.GetType() // => Student
为什么json会这样做?为什么,为什么它会使用Equals方法,以及如何使它按应有的方式运行?如果不同对象类型之间的比较不常见,那么它最终是有效的。答案应该是“否”(
false
)。因此:
及
及
(或者类似的,取决于你想要什么)
然而!您应该始终确保
GetHashCode()
与Equals()
兼容,否则等式没有完全实现(请参见)您应该在序列周围显示代码。您认为这是什么。GetType()
将在Main
类中返回?为什么在Equals
覆盖中抛出异常?如果两个对象因类型不同而不能相等,则它们不相等。这意味着,在这种情况下,应该返回false
,而不是抛出异常。请注意,Equals
参数的类型是object
,换句话说,Equals
方法明确允许测试任意对象之间的相等性,包括任意不同类型的对象……注意-如果您希望使用引用相等性,请参阅的答案中提到的解决方法。
public override bool Equals(object obj)
=> obj is Main other && Equals(Student, other.Student);
public override bool Equals(object obj)
=> obj is Student other && Age == other.Age; // && Equals(Name, other.Name) ?
public override bool Equals(object obj)
=> obj is Name other && FirstName == other.FirstName && LastName == other.LastName;