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

本文关键字:获取 属性 实例 创建对象 程序集 定名称 | 更新日期: 2023-09-27 18:28:59

我有许多具有以下模式的类:

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查询。我想从下拉框中的报告列表中动态加载类。我存储AssetyQualifiedName以及用于填充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;

我努力实现的目标可能吗?

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

除了dcastro answer的(这很好),我想建议第三种解决方案,它看起来更干净:由于"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  
}

只是为了更安全。

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

由于在编译时您不知道myObject的类型,因此您必须执行以下操作之一:

  1. 使用反射调用属性

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

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