2012-05-29 67 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

安德魯,非常感謝那 - 由於某種原因,我認爲類型需要在課堂上 –