Generic Collections - Ensuring Collections Contain Only One Type of Object?
Let me start with the definitions of the objects with which I am working and then I'll do my best to explain what I'm after:
class CacheItem<T> where T : EntityBase
class CacheCollection : List<CacheItem<EntityBase>>
OK, so my generic collection, CacheCollection should be a list of CacheItems which I can manipulate according to various business rules. One thing I'd like to ensure, howerver, is that each CacheCollection I instanciate only works for a single type of EntityBase. For instance, I have two classes inheriting from EntityBase; Case and Client. I'd like each CacheCollection to handle only one of those types and not mix them.
What changes can/should I make to accomodate this desig开发者_Python百科n requirement?
You could always make CacheCollection a generic type itself and then pass that up the inheritance tree to CacheItem:
class CacheCollection<T> : List<CacheItem<T>> where T : EntityBase
It sounds like you want to get rid of CacheCollection
(which serves no purpose) and have e.g.
List<CacheCollection<Case>> cases;
List<CacheCollection<Client>> clients;
no?
Make CacheCollection generic, so you explicitly state the type that it can contain:
class CacheCollection<T> : List<CacheItem<T>> where T : EntityBase {}
What's wrong with
class CacheCollection<T> : List<CacheItem<T>> where T:EntityBase
精彩评论