IEquatable on Self Referential类

时间:2014-11-14 17:36:35

标签: c# forms self-reference

使用表单从用户获取输入以将其创建为对象(ToDo)。信息被抛入此自引用类(ToDo)以创建对象,然后传递给另一个类Queue。

但问题是我需要将传递的以下对象与其他先前的对象进行比较。如果对象具有相同的名称,则不要将信息抛给Queue类。

但是从我的代码中,Equals方法甚至没有执行。只是想知道我在这里做错了什么。

public class ToDo : IEquatable<ToDo>
{
    private string _name;
    private string _priority;

    private ToDo _next;
    private ToDo _previous;

    Queue queue = new Queue();


    public ToDo(string name, string priority)
    {

        _name = name;
        _priority = priority;

        _next = null;
        _previous = null;

        queue.Enqueue(this);

    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public string Priority
    {
        get { return _priority; }
        set { _priority = value; }
    }

    public ToDo Next
    {
        get { return _next; }
        set { _next = value; }
    }

    public ToDo Previous
    {
        get { return _previous; }
        set { _previous = value; }
    }



    public bool Equals(ToDo other)
    {
        if (ReferenceEquals(null, other)) 
            return false;
        if (ReferenceEquals(this, other)) 
            return true;

        return other.Name.Equals(Name);
    }

    public override bool Equals(object obj)
    {
        if (Object.ReferenceEquals(null, obj))

            return false;

        if (Object.ReferenceEquals(this, obj))

            return true;

        if (this.GetType() != obj.GetType())

            return false;

        return this.Equals(obj as ToDo);

    }

    public override int GetHashCode()
    {
        return this.Name.GetHashCode();
    }



}

1 个答案:

答案 0 :(得分:0)

这是您可以使用的IEqualityComparer类。 IEqualityComparer的优点是你可以在LINQ语句中使用这个比较器,比如

var todos1 = todos2.Except(todos3, new ToDoComparer());

public class ToDoComparer : IEqualityComparer<ToDo>
{
    public bool Equals(ToDo x, ToDo y)
    {
        //Check whether the compared objects reference the same data. 
        if (ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null. 
        if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
            return false;

        return x.Name.Equals(y.Name);
    }

    public int GetHashCode(ToDo todo)
    {            
        if (ReferenceEquals(todo, null) || todo.Name == null)
            return 0;
        return todo.Name.GetHashCode();
    }
}