mercredi 4 septembre 2019

Cast to custom object at runtime

Today I have several models/classes like these:

public class Event
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Reportage
{
    public string Author { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

These are each a part of several Razor pages, that has code that is more or less 100% same but a few lines, which are not, e.g. like this one, being unique on every page:

List<Event> itemList = Utility.GetCachedData<List<Event>>("event.json");

To get a more maintainable code, I decided to try to use as much generic code as possible, and the first issue I had were how to check if a given property existed, and if, assign that one of my defaults.

For that I found how-to using reflection, and did:

var pi = itemList[0].GetType().GetProperty("Date");
if (pi != null)
    pi.SetValue(itemList[0], DateTime.Now, null);

Next step were to do something similar e.g with List<Event> itemList;, and for that I found Convert.ChangeType(object, type), and did:

var itemList =  Convert.ChangeType(itemObj, typeof(List<Event>));

The problem with this one is, that I can't do this to get/set the Date

itemList.Date

Is there a way to solve that at runtime (other than with reflection), and use standard dot notation to get/set values?





Aucun commentaire:

Enregistrer un commentaire