我在实现存储库逻辑时遇到问题。在一个真实的项目中我使用Ninject,所以我使用接口来处理某些类。现在我做了一个非常简单的问题演示:
// ------- Base User -------------- //
public interface IBaseUser
{
int Id { get; set; }
}
public class BaseUser : IBaseUser
{
public int Id { get; set; }
}
// -------- Individual User --------//
public interface IIndividualUser : IBaseUser
{
string Gender { get; set; }
}
public class IndividualUser: BaseUser, IIndividualUser
{
public string Gender { get; set; }
}
// -------- Legal User --------//
public interface ILegalUser : IBaseUser
{
string VatNumber { get; set; }
}
public class LegalUser : BaseUser, ILegalUser
{
public string VatNumber { get; set; }
}
// -------- Base User Repo --------//
public interface IBaseUserRepo<T> where T: BaseUser
{
T GetById(int id);
}
public class BaseUserRepo<T> where T : BaseUser, IBaseUserRepo<T>
{
public T GetById(int id)
{
// logic...
}
}
// -------- Individual User Repo --------//
public interface IIndividualUserRepo : IBaseUserRepo<IndividualUser>
{
IndividualUser GetByGender(string gender);
}
public class IndividualUserRepo : BaseUserRepo<IndividualUser>, IIndividualUserRepo
{
public IndividualUser GetByGender(string gender)
{
// logic...
}
}
// -------- Legal User Repo --------//
public interface ILegalUserRepo : IBaseUserRepo<LegalUser>
{
LegalUser GetByVatNumber(string vatNumber);
}
public class LegalUserRepo : BaseUserRepo<LegalUser>, ILegalUserRepo
{
public LegalUser GetByVatNumber(string vatNumber)
{
// logic...
}
}
在这两行代码中:
public class IndividualUserRepo : BaseUserRepo<IndividualUser>, IIndividualUserRepo
public class LegalUserRepo : BaseUserRepo<LegalUser>, ILegalUserRepo
编译器会触发此错误:
类型'genericInterfaceTest.IndividualUser'不能用作类型 泛型类型或方法中的参数'T' 'genericInterfaceTest.BaseUserRepo'。没有隐含的参考 从'genericInterfaceTest.IndividualUser'转换为 'genericInterfaceTest.IBaseUserRepo'。 C:\ Work \ Tests \ genericInterfaceTest \ genericInterfaceTest \ Program.cs 77 18 genericInterfaceTest
和
类型'genericInterfaceTest.LegalUser'不能用作类型 泛型类型或方法中的参数'T' 'genericInterfaceTest.BaseUserRepo'。没有隐含的参考 从'genericInterfaceTest.LegalUser'转换为 'genericInterfaceTest.IBaseUserRepo'。 C:\ Work \ Tests \ genericInterfaceTest \ genericInterfaceTest \ Program.cs 91 18 genericInterfaceTest
只有这样我才会在这行代码中实现IBaseUserRepo接口:
public class BaseUserRepo<T> where T : BaseUser, IBaseUserRepo<T>
有人可以在我错的地方解释我。
答案 0 :(得分:3)
我猜您打算在IBaseUserRepo<T>
课程中实施BaseUserRepo<T>
界面,但您所做的却是约束T
应该是基本类型BaseUser
以及T
应该实现IBaseUserRepo<T>
更改此
public class BaseUserRepo<T> where T : BaseUser, IBaseUserRepo<T>
到此
public class BaseUserRepo<T> : IBaseUserRepo<T> where T : BaseUser
现在,您已在IBaseUserRepo<T>
类中实施了BaseUserRepo<T>
接口,并将T
通用参数约束为BaseUser
。
订购事项:)