我怎样才能执行这个简单的相等比较?
我有以下代码:
public abstract class RepositoryBase<T, TId> : IRepository<T, TId>
where T : class, IEntityWithTypedId<TId>
where TId : IEquatable<TId>, IComparable<TId>
{
public T FindById(TId id)
{
T entity;
using (this.Context) // This simply returns the NHibernate Session
{
var entities = from e in this.Context.Get()
// where e.Id.Equals(id)
where e.Id == id
select e;
entity = entities.FirstOrDefault();
}
return entity;
}
}
如果我使用 where e.Id == id
子句,则会收到错误:
错误 CS0019:运算符“==”无法应用于“TId”和“TId”类型的操作数
错误的操作数,即使我已告诉编译器 TId
必须实现 IEquatable
和 IComparable
如果我使用 where e.Id.Equals(id)
子句,代码将编译,但当我从 NHibernate 收到 NotSupported 异常它在 FirstOrDefault 行上执行查询。
我知道我一定在设计中遗漏了一些东西,但是我已经好几天没有找到解决方案了。
I have the following code:
public abstract class RepositoryBase<T, TId> : IRepository<T, TId>
where T : class, IEntityWithTypedId<TId>
where TId : IEquatable<TId>, IComparable<TId>
{
public T FindById(TId id)
{
T entity;
using (this.Context) // This simply returns the NHibernate Session
{
var entities = from e in this.Context.Get()
// where e.Id.Equals(id)
where e.Id == id
select e;
entity = entities.FirstOrDefault();
}
return entity;
}
}
If I use the where e.Id == id
clause, I get the error:
error CS0019: Operator '==' cannot be applied to operands of type 'TId' and 'TId'
error even though I've told the compiler that TId
must implement IEquatable
and IComparable
If I use the where e.Id.Equals(id)
clause, the code will compile, but I get a NotSupported Exception from NHibernate when it executes the query on the FirstOrDefault
line.
I know that I must be missing something in the design however the solution has eluded me for several days.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然看起来很直观,但运算符(
==
、<
、>
等)与等接口无关>IComparable
、IEquatable
等。不幸的是,运算符不能应用于泛型类型。与
Equals
等函数不同,运算符是静态的,因此不是多态的。由于无法访问泛型类型的静态成员,因此运算符也无法访问。While it might seem intuitive, operators (
==
,<
,>
, etc.) have nothing to do with interfaces likeIComparable
,IEquatable
, etc. Unfortunately, operators can't be applied to generic types.Unlike functions like
Equals
, operators are static and therefore not polymorphic. Since it's not possible to access static members of generic types, operators are inaccessible.