首先好好看看并理解覆盖/虚拟等等。但是没有发现任何特定于我的情况的情况 - 我确信这不是唯一的。我想确保我使用的实现是正确的实现。我有以下代码设置来演示我的问题:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Sandpit
{
public class Program
{
static void Main()
{
var fixture = new Fixture
{
Name = "Fixture Name",
Participants = new List<Participant> {new Participant {Name = "Participant Name"}}
};
var writer = new StringWriter(new StringBuilder());
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter());
serializer.Serialize(writer, fixture);
Console.Write(writer.ToString());
Console.ReadKey();
}
}
public class Fixture
{
public string Name { get; set; }
public List<Participant> Participants { get; set; }
public override bool Equals(object obj)
{
var fixture = (Fixture)obj;
return fixture.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
public class Participant
{
public string Name { get; set; }
public override bool Equals(object obj)
{
var participant = (Participant)obj;
return participant.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}
现在,当这次运行时,var fixture = (Fixture)obj;
会出现异常。
无法投射类型的对象 输入'System.Collections.Generic.List`1 [Sandpit.Participant]' 'Sandpit.Fixture'。
我不明白为什么要进入那里。为什么这会破坏正确实现重写的object
方法。
我知道我可以通过public new bool Equals(object obj)
来解决这个问题。我这样做了吗?这些对象也很好地集成到我正在处理的应用程序中,是否可能有任何副作用进行此更改?
非常感谢, 马特
答案 0 :(得分:1)
对Fixture
和Participant
类进行一些小修改可以解决这个问题:
public class Fixture
{
public string Name { get; set; }
public List<Participant> Participants { get; set; }
public override bool Equals(object obj)
{
var fixture = obj as Fixture;
return fixture == null ? false : fixture.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
public class Participant
{
public string Name { get; set; }
public override bool Equals(object obj)
{
var participant = obj as Participant;
return participant == null ? false : participant.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
如果您要与另一种类型的元素进行比较,您可以确定两者不相等。