我正在为我的MVC 4项目构建(尝试构建)通用存储库,任务和控制器,并使用它来学习泛型和接口。我已经走得很远,但坚持这个错误。 CustomerContactsListViewModel继承自IViewModelList,这就是为什么我感到困惑。
错误:
The type 'OTIS.AppServ.OrderMgmt.ViewModels.CustomerContactsListViewModel' cannot be used as type parameter 'TViewModelList' in the generic type or method 'OTIS.AppServ.BaseAppServGrid<TRepository,TViewModelSingle,TViewModelList>'. There is no implicit reference conversion from 'OTIS.AppServ.OrderMgmt.ViewModels.CustomerContactsListViewModel' to 'OTIS.AppServ.IViewModelList<OTIS.domain.OrderMgmt.Customer,OTIS.AppServ.OrderMgmt.ViewModels.CustomerContactsListViewModel>'.
界面:
public interface IViewModelList<TClass, TViewModelList>
{
IEnumerable<TClass> ConvertViewModelToClass(IEnumerable<TViewModelList> entityList);
IEnumerable<TViewModelList> ConvertClassToViewModel(IEnumerable<TClass> entityList);
}
继承接口的视图模型:
public class CustomerContactsListViewModel : IViewModelList<CustomerContact, CustomerContactsListViewModel>, IEntity
继承的通用任务(应用程序服务)类:
public class BaseAppServGrid<TRepository, TViewModelSingle, TViewModelList> : BaseAppServ<TRepository, TViewModelSingle>
where TRepository : class, IEntity, IAuditStamps, new()
where TViewModelSingle : class, IViewModelSingle<TRepository, TViewModelSingle>, new()
where TViewModelList : class, IEntity, IViewModelList<TRepository, TViewModelList>, new()
尝试继承Base的特定Task / App服务类会抛出错误:
public class ManageCustomersAppServ : BaseAppServGrid<Customer, CustomerViewModel, CustomerContactsListViewModel>
答案 0 :(得分:2)
在CustomerContactsListViewModel
中,您已将IViewModelList
的第一个参数实现为CustomerContact
类型。
但是,已使用ManageCustomersAppServ
类型声明了类Customer
。
所以
IViewModelList<Customer, CustomerContactsListViewModel>
不能转发给
IViewModelList<CustomerContact, CustomerContactsListViewModel>
您需要:
更改BaseAppServGrid
以采用其他通用参数:
public class BaseAppServGrid<TModel, TRepository, TViewModelSingle, TViewModelList> :
BaseAppServ<TRepository, TViewModelSingle>
where TRepository : class, IEntity, IAuditStamps, new()
where TViewModelSingle : class, IViewModelSingle<TRepository, TViewModelSingle>, new()
where TViewModelList : class, IEntity, IViewModelList<TModel, TViewModelList>, new()
public class ManageCustomersAppServ : BaseAppServGrid<CustomerContact, Customer, CustomerViewModel, CustomerContactsListViewModel>
检查Customer 和 CustomerContact是否可以从某个IRepository接口/类派生,如果您将Customer传递给名为“TRepository”的通用参数,那么这是您的意图。
< / LI> 醇>