C# SerializeObject将自定义类型属性传递给父类型等于(对象)方法
我在Json.NETV6.0.5中看到了一些奇怪的行为,这些行为用于重写Equals方法并具有引用类型属性(除了字符串)的对象C# SerializeObject将自定义类型属性传递给父类型等于(对象)方法,c#,serialization,json.net,C#,Serialization,Json.net,我在Json.NETV6.0.5中看到了一些奇怪的行为,这些行为用于重写Equals方法并具有引用类型属性(除了字符串)的对象 public class TestObject { public ChildObject CustomTypeProperty { get; set; } public List<string> ListProperty { get; set;
public class TestObject
{
public ChildObject CustomTypeProperty
{
get;
set;
}
public List<string> ListProperty
{
get;
set;
}
public List<ChildObject> ListCustomProperty
{
get;
set;
}
public string StringProperty
{
get;
set;
}
public int IntProperty
{
get;
set;
}
public override bool Equals(object obj)
{
Console.WriteLine(obj.GetType().FullName);
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class ChildObject
{
}
公共类TestObject
{
公共ChildObject CustomTypeProperty
{
得到;
设置
}
公共列表列表属性
{
得到;
设置
}
公共列表ListCustomProperty
{
得到;
设置
}
公共字符串字符串属性
{
得到;
设置
}
公共int属性
{
得到;
设置
}
公共覆盖布尔等于(对象对象对象)
{
Console.WriteLine(obj.GetType().FullName);
返回基数等于(obj);
}
公共覆盖int GetHashCode()
{
返回base.GetHashCode();
}
}
公共类子对象
{
}
然后我序列化它
var testObj = new TestObject() { CustomTypeProperty = new ChildObject(), IntProperty = 1, ListCustomProperty = new List<ChildObject>(), ListProperty = new List<string>(), StringProperty = "abc" };
var json = JsonConvert.SerializeObject(testObj);
var testObj=new TestObject(){CustomTypeProperty=new ChildObject(),IntProperty=1,ListCustomProperty=new List(),ListProperty=new List(),StringProperty=“abc”};
var json=JsonConvert.SerializeObject(testObj);
我可以看到它调用TestObject.Equals(objectobj)三次,传入的不是TestObject,而是CustomTypeProperty对象,然后是ListProperty,然后是ListCustomProperty。在我的例子中,这会导致InvalidCastException,因为TestObject试图将obj参数强制转换为TestObject。我无法在真实场景中更改这一点,因为该类型位于第三方库中
这是Json.NET中的错误还是我做错了什么?我已经挖了一段时间,找不到任何解决办法。谢谢你的帮助
编辑
我刚刚升级到Json.NET6.0.6,看到了同样的行为 如果要实现对
bool Equals(object obj)
的覆盖,则需要处理可能传递给您的任何类型。您不能假设调用者总是传递您期望的类型。通常的解决方案是在强制转换之前进行简单的类型检查,如下所示:
public override bool Equals(object obj)
{
if (obj is TypeYouAreExpecting)
{
TypeYouAreExpecting other = (TypeYouAreExpecting) obj;
bool areEqual = false;
// implement your equals logic here
return areEqual;
}
return base.Equals(obj);
}
如果是第三方库在Equals
方法中抛出InvalidCastException
,那肯定是一个bug。我会联系作者并要求他们修复它
至于为什么Json.Net在序列化不同类型的对象时调用
Equals
,这是为了检查引用循环。更多细节请参见。我认为你根本不应该觉得自己愚蠢@r2_118=)我认为这是一种完全奇怪的行为,不应该发生。将对象传递给不同类型的equals方法非常奇怪。我现在也有同样的问题,这让我很头疼。当我问为什么在这里时,我得到了一个答案: