在我的MVC3应用程序中,我试图创建一个通用类(名为DdlGet )来调用它来获取下拉列表(DDL)的记录。不过,下面的代码是按预期做的,但我认为我过度使用了泛型类型T--特别是下面用'//**‘表示的行
我的控制器中有以下代码
private readonly IGeneralReferenceRepository<StatusType> statusTypeRepository;
...
public StatusController() : this(...new StatusTypeRepository()) {}
public StatusController(...IGeneralReferenceRepository<StatusType> statusTypeRepository)
{
...
this.statusTypeRepository = statusTypeRepository;
}
...
public ViewResult Index()
{
...
//**** The line below passes a variable (statusTypeRepository) of the Generic
//**** type (StatusType) and additionally calls the class (Helper<StatusType>)
//**** with the Generic
indexViewModel.StatusTypes = Helper<StatusType>.DdlGet(statusTypeRepository);然后在我的存储库中(这定义了通过实体框架方法从数据库中获取DDL记录的实现)--注意通用参考泛型接口(IGeneralReferenceRepository)
public class StatusTypeRepository : IStatusTypeRepository, IGeneralReferenceRepository<StatusType>
{
...
public IQueryable<StatusType> All
{
get { return context.StatusTypes; }
}我有一个接口(它对应于上面调用的All方法)
public interface IGeneralReferenceRepository<T>
{
IQueryable<T> All { get; }
}和一个帮助类,以获取下拉列表记录并放置到SelectList中。
public class Helper<T>
{
public static SelectList DdlGet(IGeneralReferenceRepository<T> generalReferenceRepository)
{
return new SelectList(generalReferenceRepository.All, ...);
}
}我遇到的问题是上面第一个代码块中指示的行,即对填充SelectList的最终实现的调用。
indexViewModel.StatusTypes = Helper<StatusType>.DdlGet(statusTypeRepository); 正如上面在注释(前缀为//**)中解释的那样,它传递一个泛型statusTypeRepository,它通过行定义类型:-
private readonly IGeneralReferenceRepository<StatusType> statusTypeRepository;不过,我已经在Helper泛型类(即Helper类)中定义了该类型。
我的问题是,我可以从另一个派生出一个,而不是在调用中两次指定泛型。也就是说,我是否可以从Helper类类型派生statusTypeRepository中指定的类型,反之亦然?
非常感谢
特拉维斯
发布于 2012-05-30 00:17:38
与其在Helper类中使用类型参数,不如将其放在下面的方法上:
public class Helper
{
public static SelectList DdlGet<T>(IGeneralReferenceRepository<T> generalReferenceRepository)
{
return new SelectList(generalReferenceRepository.All, ...);
}
}那你就可以
indexViewModel.StatusTypes = Helper.DdlGet(statusTypeRepository); 编译器将处理类型推断。
https://stackoverflow.com/questions/10808328
复制相似问题