2017-03-27 85 views
2

我有一個帶有通用標識符類型的MyUser類。 UserManager類具有方法GetByIdentifier,其將給定的標識符與已知的用戶標識符進行比較。問題是,我得到以下錯誤:簡單通用類型比較

Operator '==' cannot be applied to operands of type 'TUserIdentifier' and 'TUserIdentifier'

public MyUser<TIdentifier> 
{ 
    public TIdentifier Identifier { get; set; } 
} 

public class UserManager<TUser, TUserIdentifier> 
    where TUser : MyUser<TUserIdentifier> 
{ 
    protected List<TUser> userStore = new List<TUser>(); 
    protected TUser GetByIdentifier(TUserIdentifier identifier) 
    { 
     return userStore.FirstOrDefault(c => c?.Identifier == identifier); 
    } 
} 

當我UserManager的簽名更改爲以下我不能定義簡單類型爲intstring ECT爲TUserIdentifier了。

public class UserManager<TUser, TUserIdentifier> 
    where TUser : MyUser<TUserIdentifier> 
    where TUserIdentifier : class 

一種解決方法是使用了IntegerString等類。


另一件事我想這樣做是以下簽名,但沒有奏效

public class UserManager<TUser, TUserIdentifier> 
    where TUser : MyUser<TUserIdentifier> 
    where TUserIdentifier : IComparable 

我應該去的IntegerString等類或有另一種方式?

+0

http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c – CodeCaster

+0

@CodeCaster據我所知這篇文章基本上說我必須使用引用類型讓編譯器知道類型可以相媲美(可以應用操作符)。因此,我必須使用int,string等的引用類型實現。是嗎? – NtFreX

+0

此外,您可以使用TUserIdentifier:對象。這應該工作我認爲。 – Sebi

回答

4

這裏的問題是,編譯器無法確定您是否錯誤地執行了兩個值類型之間的引用相等性檢查; ReferenceEquals(1, 1)總是false,引用相等與值類型無關!

由於您的泛型不受引用類型限制(class約束),因此編譯器不支持==運算符,因爲其默認實現精確地是引用相等。

要避免此問題,請使用虛擬Equals方法。

+0

感謝那正是我正在尋找的 – NtFreX

+2

@ Dr.Fre考慮一下,如果可能,將'TUserIdentifier'約束爲'IEquatable '以避免不必要的裝箱。 – InBetween