从程序集限定名称创建对象实例并获取属性值

时间:2014-11-04 16:00:39

标签: c# dynamic reflection

我有许多具有以下模式的课程:

namespace MyCompany.MyApplication.ReportingClasses
{
public class ReportingClassName
{
    public string HTMLReportString {get; private set;}

    ReportingClassName()
    {
        // Use linq to generate report;
        // Populate gridview, pass object to function which returns HTMLString;
        // set HTMLReportString property;
    }

}
}

每个类根据报告保存不同的linq查询。我想从下拉框中的报告列表中动态加载类。我存储AsseblyQualifiedName以及显示名称以填充DDL。我根据我见过的帖子使用了反射,但我似乎无法执行我想要的内容;

string myAssembly = "AssemblyName"; // This is static;
string myClass = "AssemblyQualifiedName"; // This value from DDL;
var myObject = Activator.CreateInstance(AssemblyName, AssemblyQualifiedName);

string propertyValue = myObject.HTMLReportString;

"UpdatePanelID".InnerHTML = propertyValue;

我想要完成的是什么?

2 个答案:

答案 0 :(得分:2)

myObject的类型为object,因此很明显它没有任何名为HTMLReportString的属性。

由于您在编译时不知道myObject的类型,因此您必须:

  1. 使用反射来调用属性

    string value = (string) myObject.GetType()
                                    .GetProperty("HTMLReportString")
                                    .GetValue(myObject); 
    
  2. 使用动态输入

    dynamic myObject = //...
    string value = myObject.HTMLReportString;
    

答案 1 :(得分:2)

除了dcastro答案(这是好的),我想建议第三个解决方案,对我来说看起来更清洁:因为“ReportingClassName”是你自己的代码,你可以修改它以使它实现一个接口提供您所需要的:

namespace MyCompany.MyApplication.ReportingClasses
{
public interface IReporting
{
    string HTMLReportString {get;}    
}

public class ReportingClassName : IReporting
{
    public string HTMLReportString {get; private set;}

    ReportingClassName()
    {
        // Use linq to generate report;
        // Populate gridview, pass object to function which returns HTMLString;
        // set HTMLReportString property;
    }

}
}


string myAssembly = "AssemblyName"; // This is static;
string myClass = "AssemblyQualifiedName"; // This value from DDL;
var myObject = Activator.CreateInstance(AssemblyName, AssemblyQualifiedName);

string propertyValue = ((IReporting)myObject).HTMLReportString; // Thanks to the interface, myObject provides HTMLReportString and it doesn't need reflection neither "dynamic".

"UpdatePanelID".InnerHTML = propertyValue;

对于最后一部分,你也可以这样做:

string propertyValue; 
var myReport = myObject as IReporting
if(myReport != null)   
{ 
    propertyValue = myReport.HTMLReportString; 
}
else 
{ 
    // Handle the error  
}

只是为了更安全。

相关问题