我尝试使用可选的泛型类型创建方法,以便最大限度地减少SQL数据库上的查询数量。 (如果数据已经可用,则无需运行查询)
// Returns proper DataTable for selected Schedule
public static DataTable BuildReportTable<T>(Report report, List<T> InputList = null)
{
switch (report.ReportBase)
{
// Work Order Report
case 1:
List<ReportWorkOrder> wos = new List<ReportWorkOrder>();
if (InputList == null)
{
// Build WorkOrderReportList for report if none was passed
PullSQLData(() =>
{
wos = MPulseQueries.WorkOrderTableQuery();
}, 30, 46, "Failed to pull Work Order Data to generate table");
}
else
{
// If WorkOrderReportList was passed, use it
wos = InputList as List<ReportWorkOrder>;
}
switch (WOFilters[report.Filter][0])
{
case 0: //If all work orders report
return AllWOTable(report, wos);
case 1: //If open non PM work orders report
return OpenNonPMTable(report, wos);
case 2: //If open PM work orders report
return PMTable(report, wos);
case 3: //If open fluid change work orders report
return FluidChangeTable(report, wos);
case 4: //If custom filter work orders report
return CustomFilterTable(report, wos);
default:
return new DataTable();
}
default:
return new DataTable();
}
}
此代码编译时没有任何问题,并按预期执行。我唯一的问题是,为了在没有可选参数的情况下调用此方法,我必须手动指定一个Type。
DataTable DisplayedWorkOrders = BuildReportTable<ReportWorkOrder>(report);
所以,对于我的问题:有没有办法可以在方法中设置默认类型,这样我每次调用它都不需要指定?
答案 0 :(得分:1)
您可以添加非泛型重载:
public static DataTable BuildReportTable(Report report)
{
return BuildReportTable<ReportWorkOrder>(report);
}
这是一个普遍而且非常受人尊敬的习惯用法(好吧,未使用的类型参数只是让我感到有点沮丧,但我会克服它)。
否则,你会陷入困境;参数必须流动,更不用说如何。