简体   繁体   中英

Generic type constrain for ValueType in C#

I have generic class that restricts arguments to use int or long types. My issue that I need to compare variables of this argument type in my method. But compiler said that I can't compare these items -

Operator '==' cannot be applied to operands of type 'K' and 'K'

My code:

public class MyClass<T,K>
    where T : Entity<K>
    //where K : ??? - what can I do?
{
    public virtual bool MyMethod(T entity1, T entity2)
    {
        return entity1.EntityId == entity2.EntityId;//Operator '==' cannot be applied to operands of type 'K' and 'K'
    }
}
public abstract class Entity<T>
{
    public T EntityId{get;set;}
}

Instead of using the == operator, you can always use the static object.Equals(object, object) method .

That object will invoke the - possibly overridden - Equals method of whatever is passed to it, which, for value types, should be implemented to support value equality.

So, your method could be written like this:

public virtual bool MyMethod(T entity1, T entity2)
{
    return object.Equals(entity1.EntityId, entity2.EntityId);
}

You wouldn't need an extra constraint, and in fact, it would even still work in some way if T were a reference type.

You can constraint K on IEquatable<K> and use Equals :

public class MyClass<T,K>
    where T : Entity<K>
    where K : IEquatable<K>
{
    public virtual bool MyMethod(T entity1, T entity2)
    {
        return entity1.EntityId.Equals(entity2.EntityId);
    }
}

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