我怎样才能执行这个简单的相等比较?

发布于 2025-01-05 21:28:19 字数 1046 浏览 4 评论 0原文

我有以下代码:

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 必须实现 IEquatableIComparable

如果我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

So要识趣 2025-01-12 21:28:19

虽然看起来很直观,但运算符(==<> 等)与 等接口无关>IComparableIEquatable 等。不幸的是,运算符不能应用于泛型类型。

Equals 等函数不同,运算符是静态的,因此不是多态的。由于无法访问泛型类型的静态成员,因此运算符也无法访问。

While it might seem intuitive, operators (==, <, >, etc.) have nothing to do with interfaces like IComparable, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文