【发布时间】:2013-12-29 03:10:10
【问题描述】:
我正在尝试编写一个传递泛型参数的方法,该方法将使用泛型参数扩展一个类,但我不想将第二个泛型参数传递给该方法。有没有办法在不传递两个通用参数的情况下实现我想要做的事情?
// 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 {
}
【问题讨论】: