我有一个泛型类,它限制参数使用 int
或 long
类型。我的问题是我需要在我的方法中比较这种参数类型的变量。但是编译器说我无法比较这些项目 -
Operator '==' cannot be applied to operands of type 'K' and 'K'
我的代码:
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;}
}
最佳答案
除了使用 ==
运算符,您始终可以使用静态 object.Equals(object, object)
method .
该对象将调用 - 可能被覆盖 - Equals
method传递给它的任何东西,对于值类型,应该实现它以支持值相等。
所以,你的方法可以这样写:
public virtual bool MyMethod(T entity1, T entity2)
{
return object.Equals(entity1.EntityId, entity2.EntityId);
}
你不需要额外的约束,事实上,如果 T
是一个引用类型,它甚至会以某种方式工作。
关于c# - C# 中值类型的通用类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30348555/