C# 4.0 - 创建泛型类 C#
本文关键字:泛型类 创建 | 更新日期: 2023-09-27 17:55:59
我正在处理实体列表的存储库,我应该多次重复同一个类,唯一的区别是类型类型..有没有办法使其通用?
这应该很容易,当然我不知道如何制作这个通用:
private Namespace.DAL.UserProfileRepository _rep = new Namespace.DAL.UserProfileRepository();
我重复的类是这样的:
public class UserProfileRepository : IEntityRepository<IUserProfile>
{
private Namespace.DAL.UserProfileRepository _rep = new Namespace.DAL.UserProfileRepository();
public IUserProfile[] GetAll()
{
return _rep.GetAll();
}
public IUserProfile GetById(int id)
{
return _rep.GetById(id);
}
public IQueryable<IUserProfile> Query(Expression<Func<IUserProfile, bool>> filter)
{
return _rep.Query(filter);
}
}
@NickBray一
针见血。无论实际的具体存储库实现有多大不同或相似,示例中的DAL
类都应通过接口公开存储库实例。
理想情况下,公开的接口将被声明为类似的东西。
interface IUserProfileRepository : IEntityRepository<IUserProfile>
{
}
这样,您可以根据需要添加自定义IUserProfile
方法。虽然IEntityRepository
接口定义了常用的方法Add
、Update
、Remove
和各种QueryXXX
方法。
我希望这个例子对你有帮助。如果我正确理解了您的问题,您希望基于界面"IEntityRepository"使您的存储库可生成。
尝试这样的事情:
public class UserProfileRepository<TUserProfile> : IEntityRepository<TUserProfile> where TUserProfile : IUserProfile
{
private Namespace.DAL.UserProfileRepository _rep = new Namespace.DAL.UserProfileRepository();
public TUserProfile[] GetAll()
{
return _rep.GetAll();
}
public TUserProfile GetById(int id)
{
return _rep.GetById(id);
}
public IQueryable<TUserProfile> Query(Expression<Func<TUserProfile, bool>> filter)
{
return _rep.Query(filter);
}
}