Unable to compare common values

I create a generic class for storing widgets, and it's hard for me to implement the contains method:

public class WidgetBox<A,B,C>
{
    public bool ContainsB(B b)
    {
        // Iterating thru a collection of B's
        if( b == iteratorB )  // Compiler error.
        ...
    }
}

Error: the operator '==' cannot be applied to operands of types 'V' and 'V'

If I cannot compare types, how should I implement? How do dictionaries, lists, and all other common containers do this?

+5
source share
6 answers

Here you have several options.

First use Object.Equals:

if(b.Equals(iteratorB)) {
    // do stuff
}

, ; B Object.Equals, , B , B . , , .

-, , B IComparable:

public class WidgetBox<A, B, C> where B : IComparable 

if(b.CompareTo(iteratorB) == 0) {
    // do stuff
}

, IEqualityComparer<B> WidgetBox

public class WidgetBox<A, B, C> {
    IEqualityComparer<B> _comparer;
    public WidgetBox(IEqualityComparer<B> comparer) {
        _comparer = comparer;
    }
    // details elided
}

:

if(_comparer.Equals(b, iteratorB)) {
    // do stuff
}

, EqualityComparer<T>.Default:

public WidgetBox() : this(EqualityComparer<T>.Default) { }
+7

==, Equals ( Object.Equals).

public class WidgetBox<A,B,C>
{
    public bool ContainsB(B b)
    {
        // Iterating thru a collection of B's
        if( b.Equals(iteratorB) )
        ...
    }
}
+3

, where T : IEquatable<T>, IComparable. Equals, T.

public class WidgetBox<A,B,C> where B : IEquatable<B>
{
    public bool ContainsB(B b)
    {
        // Iterating thru a collection of B's
        if( b.Equals(iteratorB) )
        ...
    }
}

Object.Equals, ( ) (, , Person SSN, - ).

" .NET", , Equals ( ) - .

+3

, B .

:

var comparer = EqualityComparer<B>.Default;
foreach (B item in items) {
    if ( comparer.Equals(b, item) ) {
        ....
    }
}
+2
if (b != null)
    if (b.Equals(iteratorB))
        ...
0

If you can leave with him in your case, then all that is required is a class restriction on B

public class WidgetBox<A,B,C> where B : class

which will fix the problem

0
source

All Articles