简体   繁体   中英

Best way to maintain references to a collection of generic types

Say I have this interface:

public interface IRepository<T> where T : Entity
{
  T Get(string query);
  void Save(T entity);
}

And I have a couple of concrete classes like (where User and Project, of course, inherit from Entity):

public class UserRepository : IRepository<User> { ... }
public class ProjectRepository : IProjectRepository<Project> { ... }

What is the best way to keep a reference to all those in a single collection? You obviously can't have something like:

var repos = new IRepository<Entity>[]
{
  new UserRepository(),
  new ProjectRepository()
}

So must I have a non-generic interface from which the generic interface inherits?

public interface IRepository
{
  Entity Get(string query);
  void Save(Entity entity);
}

public interface IRepository<T> : IRepository { ... }

Thanks for any help, ideas, suggestions.

Your IRepository<T> interface doesn't really lend itself to co- or contra-variance, since T appears in both input and output positions. The best you can really do here is provide a non-generic interface as you point out.

You could, of course, store references to any type using object - but I'm guessing that you're looking for something more typesafe than that.

So must I have a non-generic interface from which the generic interface inherits?

Yes. You could put fewer methods on that non-generic interface, if you can get away with it: it depends how much type casting you wanted to do. (You could put them in an object[] , for instance.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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