1

首先,环顾四周并了解覆盖/虚拟等。但没有发现任何特定于我的情况的案例——我敢肯定这不是唯一的。我只想确保我使用的实现是正确的实现。我有以下代码设置来演示我的问题:

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)。我这样做对吗?这些对象也很好地集成到我正在处理的应用程序中,进行此更改是否可能有任何副作用?

非常感谢,马特

4

1 回答 1

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();
    }
}

如果要与另一种类型的元素进行比较,则可以确定两者不相等。

于 2013-04-05T09:17:25.523 回答