Reputation: 10476
I'm trying to write a method that passes a generic argument that will extend a class with a generic argument, but I don't want to have to pass a second generic argument to the method. Is there a way to achieve what I'm trying to do without passing two generic arguments?
// 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 {
}
Upvotes: 3
Views: 239
Reputation: 100527
I think you want something like this
public ActionResult ReportView<T>(BaseReportViewModel<T> viewModel)
where T : ReportBaseData
Side note: You also should not need to pass type in this.ReportView<Report1ViewModel>(viewModel);
call, just ReportView(viewModel);
should be enough as type should be derived from the argument.
Upvotes: 4