【问题标题】:C# Extend Generic Class in Method callC# 在方法调用中扩展泛型类
【发布时间】: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 {
}

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    我想你想要这样的东西

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

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

    【讨论】:

    • 如果我将对象作为BaseReportViewModel传入,该方法会丢失子类型吗?这意味着我需要将 Data 对象的类型传递给 ReportView 方法?
    • 现在试试这个...我想这可能行得通!我会尽快回复反馈。
    • @AdamLevitt 如果您执行BaseViewModel m = new BaseReportViewModel&lt;Report1Data&gt;(),那么您已经丢失了子类型的编译时间信息,并且通用代码将无法找到正确的类型(因为它是编译时间操作)。如果你只是使用var m = Report1ViewModel() 应该没问题。
    • 是的,我正在使用 var。使用这种方法,我如何在 razor @model 声明中引用扩展的泛型类型?
    • @AdamLevitt 不确定您的问题是什么...您是在问是否可以使用@model Report1ViewModel@model BaseReportViewModel&lt;Report1Data&gt;?或者您正在尝试制作接受所有派生类的页面(如非法@model BaseReportViewModel&lt;T&gt;)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多