开发者

IEquatable from class not being used (question about Lists)

I have a class defined as

class MyClass : IMyClass, IEquatable<MyClass>
{
  //appropriately defined bool Equals开发者_JAVA技巧(MyClass other) and int GetHashCode() methods
}

When I call the following code:

List<MyClass> list = new List<MyClass>();
//fill list here and then call distinct
var distinctList = list.Distinct(); 

in the above code, distinct correctly calls MyClass.Equals

but if I instead use the interface for the definition of the list (as shown below), the Equals from MyClass does not get called:

List<IMyClass> list = new List<IMyClass>();
//fill list here with objects of type MyClass
var notADistinctList = list.Distinct();

in the above code - notADistinctList is not a distinct list because it looks like the Equals operator from MyClass is not being called and the base Object.Equals is being called.

If I create an IEqualityComparer for IMyClass and provide that to the Distinct method, then it works.

list.Distinct(new MyClassComparer());

where MyClassComparer is defined as:

class MyClassComparer: IEqualityComparer<IMyClass>

My question is why does the Equals operator on MyClass not get called when I define my list as List < IMyClass >, but does get called when I define the list as List< MyClass >? (after MyClass is an implementation of IMyClass).


Your interface doesn't implement IEquatable, only your concrete class does. When comparing them, it doesn't care what concrete class you are using (because you said it was an interface).

Try something like this:

public class MyClass : IMyClass
{
    public bool Equals(IMyClass other)
    {       
    }
}

public interface IMyClass : IEquatable<IMyClass>
{

}


I figured out the solution,

My problem in the above code is that IEquatable was defined on MyClass.

Instead if I defined it (IEquatable) on IMyClass, then that fixes the issue.

interface IMyClass: IEquatable<IMyClass>{}

class MyClass: IMyClass
{
 //appropriately defined bool Equals(IMyClass other) and int GetHashCode() methods
}

Obviously as noted in my question, the other solution is to provide an IEqualityComparer to the Distinct method.

Though I still would like to know why the Equals method from MyClass was not automatically called on a List of IMyClass (as the objects in the list are all of type MyClass).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜