IEntity 和 IComparable 之间的类型参数转换
本文关键字:类型参数 转换 IEntity IComparable 之间 | 更新日期: 2023-09-27 18:31:47
我实现了一个抽象CustomUser
类来自定义 Asp.Net 标识,如下所示:
public abstract class CustomUser<TKey, TContext> : IUser<TKey>, IEntity<TKey>
where TKey : struct, IComparable<TKey>, IEquatable<TKey>
where TContext : DataContextBase
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public TKey Id { get; set; }
public string UserName { get; set; }
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(CustomUserManager<CustomUser<TKey, TContext>, TKey, TContext> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
其中IEntity
是:
public interface IEntity<T>
where T : IComparable
{
T Id { get; set; }
}
可比性是:
public interface IComparable<in T>
{
int CompareTo(T other);
}
IEquatable<T>
是(UserManager
要求):
public interface IEquatable<T>
{
bool Equals(T other);
}
但是我收到以下错误:
类型
'TKey'
不能用作泛型中的类型参数'TKey'
类型或方法'XXX.CustomUserManager<TUser,TKey,TContext>'
.有 没有装箱转换或类型参数从'TKey'
转换为'System.IEquatable<TKey>'
.
TKey
继承IComparable
和IEquatable
,否则我会收到更多错误。你能解释一下为什么会发生这种冲突吗?
我认为它应该是一些隐式运算符,但没有办法在这 2 个接口之间强制转换
public static implicit operator IEquatable<T> (IComparable<T> obj)
{
return ???;
}
也许你可以尝试扩展IEntity来实现IEquatable。
公共接口 IEntity 其中 T : IComparable, IEquatable