我已经为我的存储库创建了这个接口。
public interface IRepository<T, in TKey> where T: class
{
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
IEnumerable<T> FindAll();
T FindSingle(TKey id);
void Create(T entity);
void Delete(T entity);
void Update(T entity);
}
该FindSingle
方法接受一个 ID,该 ID 将用于搜索主键。通过使用in
,我希望我只被允许将引用类型作为TKey
. 出于好奇,我决定创建一个具体类并将其指定为 int,这样我就可以看到异常。
我查了MSDN,它指定这不应该工作
引用类型支持泛型类型参数中的协变和逆变,但值类型不支持它们。
我创建的类看起来像这样
public class ProjectRepository : IRepository<Project,int>
{
public IEnumerable<Project> Find(Expression<Func<Project, bool>> predicate)
{
throw new NotImplementedException();
}
public IEnumerable<Project> FindAll()
{
throw new NotImplementedException();
}
public Project FindSingle(int id)
{
throw new NotImplementedException();
}
public void Create(Project entity)
{
throw new NotImplementedException();
}
public void Delete(Project entity)
{
throw new NotImplementedException();
}
public void Update(Project entity)
{
throw new NotImplementedException();
}
}
为什么我在指定TKey
为值类型的构建时没有得到异常?另外,如果我in
从我的参数中删除了我失去了什么?MSDN 文档说逆变允许使用较少派生的类型,但通过删除in
我可以肯定地传递任何类型,因为它仍然是通用的。
这可能表明对逆变和协方差缺乏了解,但这让我有点困惑。