我有一個帶有通用標識符類型的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
的簽名更改爲以下我不能定義簡單類型爲int
,string
ECT爲TUserIdentifier
了。
public class UserManager<TUser, TUserIdentifier>
where TUser : MyUser<TUserIdentifier>
where TUserIdentifier : class
一種解決方法是使用了Integer
,String
等類。
另一件事我想這樣做是以下簽名,但沒有奏效
public class UserManager<TUser, TUserIdentifier>
where TUser : MyUser<TUserIdentifier>
where TUserIdentifier : IComparable
我應該去的Integer
,String
等類或有另一種方式?
http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c – CodeCaster
@CodeCaster據我所知這篇文章基本上說我必須使用引用類型讓編譯器知道類型可以相媲美(可以應用操作符)。因此,我必須使用int,string等的引用類型實現。是嗎? – NtFreX
此外,您可以使用TUserIdentifier:對象。這應該工作我認爲。 – Sebi