2011-05-24 78 views
2

我正在导出报告,并且我注意到我正在为每个报告复制大量代码。我想把它放在一个单独的类的方法中,但我不确定在经过一些研究之后如何去做实例化。我的代码如下:c#使用反射动态实例化

ActiveReport rpt = new Reports.rptContractListing_Merchant(); 
    rpt.Run(); 
    try 
    { 
     rpt.Run(false); 
    } 
    catch (DataDynamics.ActiveReports.ReportException eRunReport) 
    { 
     // Failure running report, just report the error to the user: 
     Response.Clear(); 
     Response.Write("<h1>Error running report:</h1>"); 
     Response.Write(eRunReport.ToString()); 
     return; 
    } 
    XlsExport xls = new XlsExport(); 
    xls.MinColumnWidth = (float)0.5; 
    xls.Export(rpt.Document, m_stream); 
    m_stream.Position = 0; 
    Response.ContentType = "application/vnd.ms-excel"; 
    Response.AddHeader("content-disposition", "inline; filename=ContractListing_Merchant.xls"); 
    System.IO.MemoryStream m_stream = new System.IO.MemoryStream(); 
    Response.BinaryWrite(m_stream.ToArray()); 
    Response.End(); 

这里是我不确定与反射部分:

ActiveReport rpt = new Reports.rptContractListing_Merchant(); 

又如:

ActiveReport rpt = new Reports.rptContractDetails(); 
    try 
    { 
     rpt.Run(false); 
    } 
    catch (DataDynamics.ActiveReports.ReportException eRunReport) 
    { 
     // Failure running report, just report the error to the user: 
     Response.Clear(); 
     Response.Write("<h1>Error running report:</h1>"); 
     Response.Write(eRunReport.ToString()); 
     return; 
    } 

    Response.ContentType = "application/pdf"; 
    Response.AddHeader("content-disposition", "inline; filename=ContractDetails.pdf"); 

    PdfExport pdf = new PdfExport(); 
    System.IO.MemoryStream memStream = new System.IO.MemoryStream(); 
    pdf.Export(rpt.Document, memStream); 
    Response.BinaryWrite(memStream.ToArray()); 
    Response.End(); 
+0

你的意思是你想要一个函数接受一个类型为'Reports.rptContractListing_Merchant'的对象,然后运行其余的函数? – Rup 2011-05-24 16:00:16

+0

您可能想向我们展示来自*两个*报告的代码,因此我们可以看到它的哪些部分是重复的,并且可以给出代码重构它的最佳方式的代码示例。这也适用于http://refactormycode.com – StriplingWarrior 2011-05-24 16:06:35

+0

@rup是的,那正是我想要做的。 – 2011-05-24 16:08:58

回答

1

你有多种选择,其中很多甚至不需要反思。

如果您可以保证所有报表类都具有“默认”构造函数(不带参数),则可以使用泛型并指定泛型类型必须具有默认构造函数。那么你可以只说new T()

否则,您可以使用依赖注入来创建基于给定类型的报表,或者您可以让您的方法将报表本身作为参数(必须由调用方法提供),并占据自己剩下的重复代码。

+1

我想他们都从'ActiveReport'继承。所以,当Brandon评论自己时,他可以将ActiveReport传递到他的功能中。 – Rup 2011-05-24 16:24:58

3

我觉得Activator.CreateInstance<T>()是去哪里T是报告要生成

+0

这就是我想要做的,但我无法弄清楚它的正确语法。 – 2011-05-24 16:14:12

0

类型我刚刚通过了RPT物体与它的代码的方法方式。有效。