mardi 11 juin 2019

Populating a Dictionary from a Class using Reflection

I want to use a dictionary to replace words in a HTML template between two $ signs. I've got it working when I add the keys myself, but I want to be able to replace using reflection, so that if I give this project to someone else, then they only need to change the class and the template keys.

I've got the Class with some properties:

public class FeedMessageValue
{
    public string Username { get; set; }
    public string SubscriptionID { get; set; }
    public DateTime MessageTime { get; set; }
    public string Subject { get; set; }
}

I populate this Class using:

feedMessageValue = new FeedMessageValue
{
      Username = username
    , SubscriptionID = subscriptionID
    , MessageTime = messageTime
};

And then try to populate the dictionary using:

PropertyInfo[] infos = feedMessageValue.GetType().GetProperties();
foreach (PropertyInfo info in infos)
{
    getMergeValues().Add(info.Name, info.GetValue(feedMessageValue, null).ToString());
}

So, in theory one of the dictionary keyvalue pairs should now be {"Username", username}, but using my code to replace for $Username$, then it throws a bug with that there is no key for Username.





Aucun commentaire:

Enregistrer un commentaire