vendredi 6 mars 2020

How can I use reflection to dynamically cast one object to another?

I am trying to set up the following code:

Controller

[HttpGet]
public ActionResult LoadReport(string actionName, string reportInput, string reportCriteria)
{
    var type = Assembly.Load("Company.TaxCollection.Reports").GetTypes().First(t => t.Name == reportInput);
    var typeCriteria = Assembly.Load("Company.TaxCollection.Reports").GetTypes().First(t => t.Name == reportInput + "Criteria");
    var reportObject = Activator.CreateInstance(type);
    var reportObjectCriteria = Activator.CreateInstance(typeCriteria);
    IEnumerable<ReportCriteria> reportList = getReportCriteria(reportObject);
    foreach (ReportCriteria r in reportList)
    {
        reportObjectCriteria t = (reportObjectCriteria)r;
    }

    return Json(Url.Action(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria)));
}

I get the error reportObjectCriteria is a variable but is used like a type within the foreach loop.

I have also tried not using a variable and just using Activator.CreateInstance directly, but that didn't work either.

foreach (ReportCriteria r in reportList)
{
Activator.CreateInstance(typeCriteria) t = 
(Activator.CreateInstance(typeCriteria)) r;
}

The purpose of these lines of code is to cast the ReportCriteria object to another type dynamically during runtime. The object type to cast to is decided by the reportInput parameter in the controller.





Aucun commentaire:

Enregistrer un commentaire