更换为大的开关? [英] Replacement for big switch?
问题描述
我有一个名为ReportController.aspx,其目的是实例基于查询字符串参数的报表(班)页
I have a page named "ReportController.aspx" whose purpose is to instantiate a report (class) based on query string parameters
switch (Request.QueryString["Report"])
{
case "ReportA":
CreateReportAReport("ReportA's Title");
break;
case "ReportB":
CreateReportBReport("ReportB's Title");
break;
case "ReportC":
CreateReportCReport("ReportC's Title");
break;
case "ReportD":
CreateReportDReport("ReportD's Title");
break;
...
基本上,需要新的报告中的每个时间会有增加的情况下,加入的方法的此开销。这个switch语句可以得到非常非常长。我读的是可以用字典来一个报表映射到?如何使用字典这个样子(假设这是一个更好的方法)。
Basically, each time a new report is needed there will be this overhead of adding a case and adding a method. This switch statement could get very very long. I read that is is possible to use a Dictionary to map a Report to ?. How would this look using a Dictionary (assuming this is a better way).
此外, CreateReportXReport
方法主要通过一堆额外的查询字符串值报告类的构造函数(每一个报表类有不同的构造函数)。
Also, CreateReportXReport
method basically passes a bunch of additional QueryString values to the report class's constructor (each report class has a different constructor).
推荐答案
假设所有报告落实的iReport
,您可以使用函数功能:LT做到这一点; iReport的>
,像这样的:
Assuming that all reports implement IReport
, you can do it using Func<IReport>
, like this:
IDictionary<string,Func<IReport>> dictToReport = new Dictionary {
{"ReportA", () => CreateReportAReport("ReportA's Title") }
, {"ReportB", () => CreateReportBReport("ReportB's Title") }
, ...
};
您可以再与该code更换开关:
You can then replace the switch with this code:
var myReport = dictToReport[Request.QueryString["Report"]]();
这篇关于更换为大的开关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!