c# - C# 中值类型的通用类型约束

标签 c# .net generics where-clause

我有一个泛型类,它限制参数使用 intlong 类型。我的问题是我需要在我的方法中比较这种参数类型的变量。但是编译器说我无法比较这些项目 -

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/

相关文章:

C# 泛型协变

c - 通用堆栈停止弹出值

c# - 无法加载文件或程序集“Microsoft.SharePoint,版本=15.0.0.0”

c# - 如何使用哈希表?

C# 到 PHP base64 编码/解码

c# - 如何将 Linq 与 CaSTLe ActiveRecord 一起使用

python - IronPython 与 numpy 的 Python 速度对比

Java:如何对待泛型异构容器?

c# - 将一个表达式作为参数传递到另一个表达式中

c# - 在 ConcurrentDictionary AddOrUpdate 中为更新部分添加什么