Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用变量创建[泛型类型]的新实例_C#_Wpf_Coding Style_Instance Variables - Fatal编程技术网

C# 使用变量创建[泛型类型]的新实例

C# 使用变量创建[泛型类型]的新实例,c#,wpf,coding-style,instance-variables,C#,Wpf,Coding Style,Instance Variables,假设我有100个reportDelete,这种编写代码的方式不是最优的。我在考虑创建一个函数,该函数基于combobox.Text的变量名,并以某种方式将其传递给一个新实例。唯一的问题是我不知道我怎么做,或者它是否可能 我努力完成的目标 if (comboBox.Text == "Report 1 Name") { Reports.reportDelete report = new Reports.reportDelete(); Preview.Doc

假设我有100个reportDelete,这种编写代码的方式不是最优的。我在考虑创建一个函数,该函数基于combobox.Text的变量名,并以某种方式将其传递给一个新实例。唯一的问题是我不知道我怎么做,或者它是否可能

我努力完成的目标

  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();
    }

一个简单的解决方案是确保每个
ReportDelete
类实现一个
IReportDelete
接口并使用
字典

Reports.(combobox.Text) report = new Reports.(comboboxText());
Preview.DocumentSource = report;
report.CreateDocument();

通过传入报表名称,可以使reportDelete类更通用吗

var report = ReportFactory[comboBox.Text];
Preview.DocumentSource = report;
report.CreateDocument();

如果你开始使用MVVM,你会发现你的代码变得更干净、更简单、更可测试和更可维护。为什么要用func作为值而不仅仅是实例?@ashburaczenko,很好的一点:我肯定在这方面做得太过火了。
var report = ReportFactory[comboBox.Text];
Preview.DocumentSource = report;
report.CreateDocument();
public class reportDelete
{
    public string ReportName { get; private set; }

    public reportDelete(string reportName)
    {
        ReportName = reportName;
    }
}

...

Preview.DocumentSource = reportDelete(combobox.Text);
report.CreateDocument();