简体   繁体   English

创建通用类C#

[英]Create Generic Class C#

I'm working on a repository for a list of entities, and I should repeat thea same class more than once, the only difference is type type .. is there a way to make it generic? 我正在为一个实体列表存储库,我应该多次重复同一个类,唯一的区别是类型type ..是否可以使其通用?

It should quite easy, for sure I don't know how to make this generic: 这应该很容易,因为我肯定不知道如何使它通用:

 private Namespace.DAL.UserProfileRepository _rep = new Namespace.DAL.UserProfileRepository();

The class I'm repeating it this: 我在课堂上重复这个:

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 hit the nail on the head. @NickBray击中了头部。 Regardless of how different or similar the actual concrete repository implementations are the DAL class in your example should expose the repository instance via an interface. 无论示例中DAL类实际的具体存储库实现有多大差异,都应该通过接口公开存储库实例。

Ideally the exposed interface would be declared something like this. 理想情况下,应将暴露的接口声明为这样。

interface IUserProfileRepository : IEntityRepository<IUserProfile>
{
}

This way you could add custom IUserProfile methods as necessary. 这样,您可以根据需要添加自定义IUserProfile方法。 While the IEntityRepository interface would define the common methods Add , Update , Remove and various QueryXXX methods. 虽然IEntityRepository接口将定义常见的方法AddUpdateRemove和各种QueryXXX方法。

I hope this example helpful for you. 我希望这个例子对您有所帮助。 If I correctly understood your question, you want to make generizable your repository based on the interface "IEntityRepository". 如果我正确理解了您的问题,那么您希望基于接口“ IEntityRepository”使您的存储库可泛化。

Try something like this: 尝试这样的事情:


    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);
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM