interface IRepository<TEntity,Tid> where TEntity :class
{
int Insert(TEntity entity);
int Delete(TEntity entity);
TEntity GetById(Tid id);
TEntity GetByFilters(TEntity entity);
int Update(TEntity entity);
}
尝试实现
internal class Repository<XYZClass, string> : IRepository<XYZCLass, string>
{
//...All interface methods
}
得到以下错误:
类型参数声明必须是标识符而不是类型
任何建议..
声明应仅包含那些对使用该类的泛型参数的类型参数。
换句话说,如果 IRepository 的实现将 TEntity 参数设置为 XYZClass,将 TID 参数设置为字符串(即具体的类定义),那么您应该具有:
internal class Repository : IRepository<XYZCLass, string>
{
//...All interface methods
}
如果您希望定义一种类型并保留另一种泛型,则:
internal class Repository<TEntity> : IRepository<TEntity, string>
{
//...All interface methods
}
否则,这两种类型仍应保持打开状态:
internal class Repository<TEntity,TID> : IRepository<TEntity, TID>
{
//...All interface methods
}
Repository
是非泛型的,则需要指定两种类型:
internal class Repository : IRepository<XYZClass, string> { ... }
如果您希望Repository
是通用的,但指定TId
是您可以使用的string
internal class Repository<TEntity> : IRepository<TEntity, string> where TEntity : class
{
//...All interface methods
}
string
是一个类型,而不是泛型类型参数。
也许你想要一个基类约束?
internal class Repository<TYourEntity> : IRepository<TYourEntity, string>
where TYourEntity : XyzClass
{
//...All interface methods
}
请注意,此约束意味着满足接口上的约束(引用类型约束 TEntity : class
)。
为了完整起见,对您的意思的其他"法律"解释(已经在其他答案中)是:
// don't constrain generic parameter, just name it TXyz (TXyz is "declared" here)
internal class Repository<TXyz> : IRepository<TXyz, string>
where TXyz : class
{
//...All interface methods
}
和:
// make class non-generic (the type XyzClass exists and is declared elsewhere)
internal class Repository : IRepository<XyzClass, string>
{
//...All interface methods
}
因此存储库不是通用的(它是使用具体类参数化的存储库接口的实现):
internal class Repository : IRepository<XYZCLass, string>