在常规列表中使用Equals方法失败

在常规列表中使用Equals方法失败

本文介绍了C#在常规列表中使用Equals方法失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中有使用模板的State类.我有一个Cell类,我将其用作State,因此State将Cell保留为genericState.现在,我有一个泛型函数,用于检查两个实例是否相等.问题是,它永远不会让State Equals方法变为Cell Equals方法.

I have a project where I have class State which uses templates.I have a class Cell, and I use it as State, so State holds a Cell as genericState.Now I have a generic function which checks if two instances are equal.Problem is, it never leaves the State Equals method to Cell Equals method.

public class State<T>
{
    public T genericState;  //in my case T is a cell
    public State(T cellState) // CTOR
    {
        this.genericState = cellState;
    }

    public override bool Equals(object obj)
    {
        return genericState.Equals((obj as State<T>).genericState);
    } //never leaves
}

和Class Cell的代码,永远不会得到:

and code of Class Cell, in which it never gets:

public class Cell
{
    public int row, col;
    public bool visited;
    public char value;
    public bool Equals(Cell other)   //never gets here
    {
       return other != null && other.row == row && other.col == col;
    }
 }

我不明白为什么它永远都无法使用Cell的Equal方法.代码有什么问题?

I don't understand why it never gets to Equal method of Cell. What could be wrong with the code?

推荐答案

问题是您的代码不知道T具有特殊方法

The problem is that your code does not know that T has a special method

bool Equals<T>(T other)

它认为它应该调用CellEquals(object)的覆盖,而您的代码不会对此覆盖.

It thinks that it should be calling Cell's override of Equals(object), which your code does not override.

这很简单:将IEquatable<Cell>添加到Cell实现的接口列表中,并在T上添加约束以确保其实现IEquatable<T>:

Fixing this is simple: add IEquatable<Cell> to the list of interfaces implemented by Cell, and add a constraint on T to ensure that it implements IEquatable<T>:

public class State<T> where T : IEquatable<T> {
    ... // The rest of the code remains the same
}
...
public class Cell : IEquatable<Cell> {
    ... // The rest of the code remains the same
}

这篇关于C#在常规列表中使用Equals方法失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:35