简体   繁体   中英

Convert EqualityComparer<Child<T>> into EqualityComparer<Parent>

I have such hierarchy :

public interface INode
{
    //...
}

public interface INode<T> : INode
{
    //...
}

public class Node : INode
{
    //...
}

public class Node<T> : Node, INode<T>
{
    //...     
}

Now I want to cast like this :

EqualityComparer<INode<int>> intcomparer = EqualityComparer<INode<int>>.Default;
EqualityComparer<INode> comparer = intcomparer;

Why this casting is invalid ? and how to fix it ?

Why should the cast be valid?

What makes you believe that EqualityComparer<T> derives from EqualityComparer<Random base class/interface of T> or EqualityComparer<every possible base class/interface of T> ?

You can't compare it to this:

Node<string> stringNode;
Node node = stringNode;

This works since your class Definition of Node<T> explicitly derives from the non-generic version of Node

public class Node<T> : Node, INode<T>

When you have a look at the class definition of EqualityComparer<T>

public abstract class EqualityComparer<T> : 
    System.Collections.Generic.IEqualityComparer<T>,
    System.Collections.IEqualityComparer

You can see there is no non-generic version, you could change your code to his though:

EqualityComparer<INode<int>> intcomparer = EqualityComparer<INode<int>>.Default;
IEqualityComparer comparer = intcomparer;

But, IEqualityComparer will have no information about your INode and only define a Equals(object, object) method.

This is valid for every generic class, eg. see this related, maybe even duplicate question:

Cast Generic<Derived> to Generic<Base>

Update:

After, noticing that IEqualityComparer<T> is defined as IEqualityComparer<in T> - so contravariant is possible, you can have a look at this:

Variance in generic Interfaces

The other way around you currently have is possible, with the interfaces IEqualityComparer<T> doesn't work on class.

IEqualityComparer<INode> comparer = EqualityComparer<INode>.Default;
IEqualityComparer<INode<int>> intcomparer = comparer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM