是短:
为什么将派生类型添加到集合会通过,但是在尝试添加派生类型的泛型时会失败?
“短”代码:
//a generic repository
public class EfRepository<T> : IRepository<T> where T: BaseCatalogModel{...}
public CatalogRepository(IRepository<Product> productRepository, IRepository<Category> categoryRepository)
{
//This passes
Dictionary<int, BaseCatalogModel> dic1 = new Dictionary<int, BaseCatalogModel>();
dic1.Add(1, new Product());
dic1.Add(2, new Category());
dic1.Add(3, new BaseCatalogModel());
//This not.
//The error: cannot convert from 'YoYo.Core.Data.Repositories.EfRepository<YoYo.Commerce.Common.Domain.Catalog.Product>'
//to 'YoYo.Core.Data.Repositories.EfRepository<YoYo.Commerce.Common.Domain.Catalog.BaseCatalogModel>'
Dictionary<int, EfRepository<BaseCatalogModel>> dic2 = new Dictionary<int, EfRepository<BaseCatalogModel>>();
dic2.Add(1, new EfRepository<Product>());
dic2.Add(2, new EfRepository<Category>());
}
长期交易:在在线商店工作,我想在目录存储库中保存与管理目录相关的所有存储库的集合。
这个想法是从一个存储库管理整个目录。
存储库集合是字典类型)
我无法将任何 BaseCatalogModel 派生类型存储库添加到集合中。
我很乐意在上述方面获得任何帮助或获得更好实施的建议。
public class BaseCatalogModel
{
public int Id { get; set; }
...
}
public class Category:BaseCatalogModel
{
...
}
public class Product : BaseCatalogModel
{
...
}
public class CatalogRepository : ICatalogRepository
{
private readonly Dictionary<Type, IRepository<BaseEntity>> _repositoriesCollection= new Dictionary<Type, IRepository<BaseEntity>>();
public CatalogRepository(IRepository<Product> productRepository, IRepository<Category> categoryRepository)
{
_repositoriesCollection.Add(typeof(Category), categoryRepository); //==> this fails
_repositoriesCollection.Add(typeof(Product), productRepository); //==> this fails
}
public T GetCatalogItem<T>(int id) where T : BaseCatalogModel
{
//returns a catalog item using type and id
}
public IEnumerable<T> GetCatalogItem<T>() where T : BaseCatalogModel
{
//returns the entire collection of catalog item
}
}