簡體   English   中英

如何執行這種簡單的相等比較?

[英]How can I perform this simple equality comparison?

我有以下代碼:

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子句, where e.Id == id收到錯誤消息:

錯誤CS0019:運算符'=='不能應用於類型'TId'和'TId'的操作數

錯誤,即使我告訴編譯器TId必須實現IEquatableIComparable

如果我使用where e.Id.Equals(id)子句,則代碼將編譯,但是當它在FirstOrDefault行上執行查詢時,會從NHibernate收到NotSupported異常。

我知道我必須在設計中遺漏某些東西,但是解決方案使我迷茫了好幾天。

盡管看似直觀,但運算符( ==<>等)與IComparableIEquatable等接口無關。不幸的是,運算符無法應用於泛型類型。

Equals函數不同,運算符是靜態的,因此不是多態的。 由於無法訪問泛型類型的靜態成員,因此無法訪問運算符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM