if (comboBox.Text == "Report 1 Name")
{
Reports.reportDelete report = new Reports.reportDelete();
Preview.DocumentSource = report;
report.CreateDocument();
}
else
{
Reports.reportDelete2 report = new Reports.reportDelete2();
Preview.DocumentSource = report;
report.CreateDocument();
}
所以说我有100个reportDelete's,这种编写这段代码的方式并不是最优的。我正在考虑创建一个函数,该函数采用基于combobox.Text的变量名,并以某种方式传递它以创建一个新实例。唯一的事情是我不知道我怎么能做到这一点,或者它是否可能。
我试图完成的事情。
Reports.(combobox.Text) report = new Reports.(comboboxText());
Preview.DocumentSource = report;
report.CreateDocument();
答案 0 :(得分:1)
一个简单的解决方案是确保每个ReportDelete
类实现IReportDelete
接口并使用Dictionary
:
private readonly Dictionary<string, IReportDelete> ReportFactory =
new Dictionary<string, IReportDelete>
{
{ "Report 1 Name", new ReportDelete1() },
{ "Report 2 Name", new ReportDelete2() },
...
};
然后将if
&#39序列替换为:
var report = ReportFactory[comboBox.Text];
Preview.DocumentSource = report;
report.CreateDocument();
答案 1 :(得分:1)
您是否可以通过传递报告名称使reportDelete类更通用?
public class reportDelete
{
public string ReportName { get; private set; }
public reportDelete(string reportName)
{
ReportName = reportName;
}
}
...
Preview.DocumentSource = reportDelete(combobox.Text);
report.CreateDocument();