我有以下通用类:
public class Entity<Key>
{
public Key ID;
}
public interface IEntity<T>
{
T ID { get; set; }
}
public class GenericRepo<TEntity,CEntity,Key>
where TEntity : class, IEntity<Key>
where CEntity : class, IEntity<Key>
{
protected readonly DataContext _context;
protected readonly IMapper _mapper;
public GenericRepo(DataContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public CEntity GetByID(Key id)
{
//here i get operators == cannot be applied to operands of type 'Key' and 'Key'
TEntity dbEntity = _context.Set<TEntity>().FirstOrDefault(e => e.ID == id);
if (dbEntity == null)
{
return null;
}
return _mapper.Map<CEntity>(dbEntity);
}
}
我正在尝试将通用类型Key
传递给ID
属性。当我在传递的参数和Set的属性(也为operators == cannot be applied to operands of type 'Key' and 'Key'
类型)上使用==
时得到Key
,因为它们是相同的通用类型Key
,如何在Key
上实现相等性在这些课程上?
我需要传递的类型是int
或string
。
但是,我尝试向类where
中添加where T : Type
子句,消除了操作数错误,但是现在我无法像下面的string
一样传递int
或Entity<int>
,但我无法获得there is no boxing conversion from int to System.Type
。] >
[我看到了一些使用类.Equals
并将IComparer实现到类的答案,但就我而言,它是一种类型,我需要==
在ef-core的LINQ to SQL中使用它。
是否有任何要添加到类的where
条件,我可以将类型传递给我的类并使用==
或任何其他方式?
我有以下通用类:公共类实体
e.ID
具有Key
类型(与id
参数相同,则应该工作。 还有一个旁注,泛型类型参数通常以大写字母T
开头,最好声明TKey
而不是Key
。它使您可以区分常规类型参数和泛型参数
您几乎必须通过IComparable或类似的界面。