【发布时间】:2020-04-13 10:55:15
【问题描述】:
我有以下通用类:
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 属性。当我在传递的参数上使用== 和同样属于Key 类型的Set 属性时,我得到operators == cannot be applied to operands of type 'Key' and '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 条件可以添加到类中,我可以将类型传递给我的类并使用== 或任何其他方式?
【问题讨论】:
-
@WaiHaLee 我看到了,几乎所有答案都使用
EqualityComparer,我希望找到一种方法通过string或int并将它们与==进行比较而无需通过IComparer 或类似接口 -
这个link 可能对你有帮助
标签: c# generics linq-to-sql