2012-05-29 65 views
1

在我的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; } 
    } 

我有一个接口(对应于在上文中被称为所有方法)

public interface IGeneralReferenceRepository<T> 
{ 
    IQueryable<T> All { get; } 
} 

和辅助类来获得下拉列表中记录并放入选择列表的

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; 

但是我已经在助手通用类中定义的类型(即助手类)

我的问题是我可以从另一个派生,而不是在调用中指定通用的两次。即我可以导出或辅助类类型的statusTypeRepository指定的类型反之亦然

非常感谢
特拉维斯

回答

1

与其让您Helper类的类型参数,你可以把它放在内方法像这样:

public class Helper 
{ 
    public static SelectList DdlGet<T>(IGeneralReferenceRepository<T> generalReferenceRepository) 
    { 
     return new SelectList(generalReferenceRepository.All, ...); 
    } 
} 

然后,你可以做

indexViewModel.StatusTypes = Helper.DdlGet(statusTypeRepository); 

和编译器将处理类型推断。

+0

安德鲁,非常感谢那 - 由于某种原因,我认为类型需要在课堂上 –