我有以下示例。
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{ ... });
我在 Main 类型的 Equals 方法中得到不同的类型,并且我会在其他 Equals 方法中假设不同的类型。
我得到的类型是,对于
this.GetType() // => Main
obj.GetType() // => Student
为什么 json 会这样做,为什么它使用 Equals 方法以及如何让它表现得像它应该的那样?
最佳答案
在不同对象类型之间进行比较最终是有效的(即使不常见)。答案应该是“否”(false
)。所以:
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;
(或类似的东西,取决于你想要什么)。
但是!您应该始终确保 GetHashCode()
与 Equals()
兼容,否则相等性未完全实现(请参阅 CS0659)
关于c# - 当对象实现 Equals 时,Newtonsoft.Json 序列化表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53596933/