C#在Method调用中扩展Generic Class

时间:2013-12-28 19:06:08

标签: c# generics

我正在尝试编写一个传递泛型参数的方法,该泛型参数将使用泛型参数扩展一个类,但我不想将第二个泛型参数传递给该方法。有没有办法在不传递两个通用参数的情况下实现我想做的事情?

// 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 {
}

1 个答案:

答案 0 :(得分:4)

我想你想要这样的东西

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

旁注:您也不需要在this.ReportView<Report1ViewModel>(viewModel);调用中传递类型,只需要ReportView(viewModel);就足够了,因为类型应该从参数派生。