在IEntity <t>和IComparable <t> </t> </t>之间输入参数转换

时间:2014-11-24 13:41:37

标签: c#

我实现了一个抽象的CustomUser类来自定义Asp.Net Identity,如下所示:

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; }
}

IComparable 是:

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会继承IComparableIEquatable,否则会收到更多错误。你能解释一下为什么会发生这种冲突吗?

1 个答案:

答案 0 :(得分:0)

我认为它应该是一些隐式运算符,但是没有办法在这两个接口之间进行转换

public static implicit operator IEquatable<T> (IComparable<T> obj)
{
    return ???;
}

也许您可以尝试扩展 IEntity 以实现IEquatable

public interface IEntity其中T:IComparable,IEquatable