vendredi 10 juin 2022

I want to set a few string properties to an Object using Reflection. How do I do that in C#? [duplicate]

I am creating a website using N-Tier with an MVC front-end in Visual Studios 2019 using .NET Framework in C#. I have a few strings that I am sending over to the model from my controller (currently hard-coded for example purposes, but in reality this information would come from the domain tier using dapper to reach my database and extract the information):

[HttpGet]
public ActionResult Index()
{
    IndexViewModel model = new IndexViewModel("a", "b", "c", "d");
    return View(model);
}

When the program gets to the model I want to take these strings and box them inside of a new private object via the constructor. Then I want to create a protected internal method called ChurchContactInformation that returns that same object unboxed with the information contained inside of it to send over to the view (cshtml page) to show to the user. This is what I have tried but I keep getting a null exception error.

private object churchInformation;

    public IndexViewModel(string churchLocation, string churchPhoneNumber, string churchEmail, string onlineWorshipLink)
    {
        
        churchInformation = new object();
        churchInformation.GetType().GetProperty(churchLocation).GetValue(churchLocation);
        churchInformation.GetType().GetProperty(churchPhoneNumber).GetValue(churchPhoneNumber);
        churchInformation.GetType().GetProperty(churchEmail).GetValue(churchEmail);
    }

    protected internal object ChurchContactInformation ()
    {
        return churchInformation.GetType().Attributes;
    }
}

I am pretty new to reflection, would anyone be able to help with this?





Aucun commentaire:

Enregistrer un commentaire