簡體   English   中英

C#在Method調用中擴展Generic Class

[英]C# Extend Generic Class in Method call

我正在嘗試編寫一個傳遞泛型參數的方法,該參數將使用泛型參數擴展一個類,但我不想將第二個泛型參數傳遞給該方法。 有沒有辦法在不傳遞兩個通用參數的情況下實現我想要做的事情?

// this base doesn't work because it expects a BaseReportViewModel<D> 
// I don't want to have to pass in two generic arguments from the child controller
// this is what I don't want to do: this.ReportView<Report1ViewModel, Report1Data>(viewModel);
// I want to ONLY have to pass in a single generic argument. 

public class BaseController {
  // the below line won't compile because it expects a generic type to be passed to BaseReportViewModel<>
  public ActionResult ReportView<T>(T viewModel) where T : BaseReportViewModel {
    viewModel.ReportGroup = this.ReportGroup;
    viewModel.ReportTitle = this.ReportTitle;
    return this.View(viewModel);
  }
}

public class ChildController {  
  var viewModel = new Report1ViewModel();               
  viewModel.Data = new Report1Data();
  return this.ReportView<Report1ViewModel>(viewModel);            
}

public class BaseReportViewModel<T> : BaseViewModel where T : ReportBaseData {
  public string ReportGroup { get; set; }
  public string ReportTitle { get; set; }
  public T Data { get; set; }
}

public class Report1ViewModel : BaseReportViewModel<Report1Data> {
}

public class Report1Data : BaseReportData {
}

我想你想要這樣的東西

public ActionResult ReportView<T>(BaseReportViewModel<T> viewModel) 
    where T : ReportBaseData 

旁注:你也不需要在this.ReportView<Report1ViewModel>(viewModel);傳遞類型this.ReportView<Report1ViewModel>(viewModel); 調用,只需ReportView(viewModel); 應該足夠,因為類型應該從參數派生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM