C# 中值类型的通用类型约束
Generic type constrain for ValueType in C#
我有通用 class 限制参数使用 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;}
}
您可以在 IEquatable<K>
上约束 K
并使用 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);
}
}
您始终可以使用静态 object.Equals(object, object)
method.
而不是使用 ==
运算符
该对象将调用 - 可能被覆盖 - Equals
method 传递给它的任何内容,对于值类型,应该实现它以支持值相等。
所以,你的方法可以这样写:
public virtual bool MyMethod(T entity1, T entity2)
{
return object.Equals(entity1.EntityId, entity2.EntityId);
}
您不需要额外的约束,事实上,如果 T
是引用类型,它甚至在某种程度上仍然有效。
我有通用 class 限制参数使用 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;}
}
您可以在 IEquatable<K>
上约束 K
并使用 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);
}
}
您始终可以使用静态 object.Equals(object, object)
method.
==
运算符
该对象将调用 - 可能被覆盖 - Equals
method 传递给它的任何内容,对于值类型,应该实现它以支持值相等。
所以,你的方法可以这样写:
public virtual bool MyMethod(T entity1, T entity2)
{
return object.Equals(entity1.EntityId, entity2.EntityId);
}
您不需要额外的约束,事实上,如果 T
是引用类型,它甚至在某种程度上仍然有效。